<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Python入门 | SanShui的个人博客</title><meta name="author" content="SanShui"><meta name="copyright" content="SanShui"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="Python入门学习">
<meta property="og:type" content="article">
<meta property="og:title" content="Python入门">
<meta property="og:url" content="https://huaiyuechusan.github.io/archives/d9ef328.html">
<meta property="og:site_name" content="SanShui的个人博客">
<meta property="og:description" content="Python入门学习">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://wallpaper.csun.site/?4">
<meta property="article:published_time" content="2023-11-19T10:16:00.000Z">
<meta property="article:modified_time" content="2024-10-17T11:57:27.193Z">
<meta property="article:author" content="SanShui">
<meta property="article:tag" content="学习技术">
<meta property="article:tag" content="Python">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://wallpaper.csun.site/?4"><link rel="shortcut icon" href="/./img/config_img/%E9%98%B3%E5%85%89%E5%B0%8F%E7%8C%AB.jpg"><link rel="canonical" href="https://huaiyuechusan.github.io/archives/d9ef328"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Python入门',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-10-17 19:57:27'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/custom.css" media="defer" onload="this.media='all'"><script src="https://npm.elemecdn.com/echarts@4.9.0/dist/echarts.min.js"></script><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-double-row-display@1.00/cardlistpost.min.css"/>
<style>#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags:before {content:"\A";
  white-space: pre;}#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags > .article-meta__separator{display:none}</style>
<link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-categories-card@1.0.0/lib/categorybar.css"><link rel="stylesheet" href="/./css/runtime.css" media="print" onload="this.media='all'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.4.2"><link rel="alternate" href="/atom.xml" title="SanShui的个人博客" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (true) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/./img/config_img/%E9%98%B3%E5%85%89%E5%B0%8F%E7%8C%AB.jpg" onerror="onerror=null;src='./img/config_img/蓝天.jpg'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">25</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">16</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope-open"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('http://wallpaper.csun.site/?4')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">SanShui的个人博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope-open"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Python入门</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-11-19T10:16:00.000Z" title="发表于 2023-11-19 18:16:00">2023-11-19</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-10-17T11:57:27.193Z" title="更新于 2024-10-17 19:57:27">2024-10-17</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Python/">Python</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">30.9k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>118分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Python入门"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p><meta name="referrer" content="no-referrer" /></p>
<h1 id="Python入门"><a href="#Python入门" class="headerlink" title="Python入门"></a>Python入门</h1><h2 id="编程基本概念"><a href="#编程基本概念" class="headerlink" title="编程基本概念"></a>编程基本概念</h2><h3 id="Python程序的构成"><a href="#Python程序的构成" class="headerlink" title="Python程序的构成"></a>Python程序的构成</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041322674.png" alt="image-20240204132244728"></p>
<ol>
<li>Python程序由模块组成。一个模块对应python源文件，一般后缀名是：.py</li>
<li>模块由语句组成。运行Python程序时，按照模块中语句的顺序依次执行</li>
<li>语句是Python程序的构造单元，用于创建对象、变量赋值、调用函数、控制语句等</li>
</ol>
<h4 id="代码的组织和缩进"><a href="#代码的组织和缩进" class="headerlink" title="代码的组织和缩进"></a>代码的组织和缩进</h4><p>很多编程语言通过字符(例如：花括号{})、关键字(例如：begain/end)来划分代码块。同时，在配合代码的缩进增加可读性。“龟叔”设计Python语言时，直接通过缩进来组织代码块。“缩进”成为了Python语法<strong>强制的规定</strong>。缩进时，几个空格都是允许的，但是数目必须统一。<strong>通常采用“四个空格”表示一个缩进</strong>。</p>
<p>同时，也要避免将“tab制表符”或者tab与空格混合的缩进风格。目前，<strong>常用的编辑器一般设置成：tab制表符就是4个空格</strong></p>
<h4 id="使用-行连接符"><a href="#使用-行连接符" class="headerlink" title="使用\行连接符"></a>使用<code>\</code>行连接符</h4><p>一行程序长度是没有限制的，但是为了可读性更强，通常将一行比较长的程序分为多行。这是，我们可以使用<code>\</code>行连接符，把它放在行结束的地方。Python解释器仍然将它们解释为同一行。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">40</span>,\</span><br><span class="line">   <span class="number">50</span>,<span class="number">60</span>,<span class="number">70</span>,\</span><br><span class="line">   <span class="number">80</span>,<span class="number">90</span>,<span class="number">100</span>]</span><br><span class="line">b = <span class="string">&#x27;abcdefg\</span></span><br><span class="line"><span class="string">     hijklmn\</span></span><br><span class="line"><span class="string">     opqrst\</span></span><br><span class="line"><span class="string">     uvwxyz&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(a)</span><br><span class="line"><span class="built_in">print</span>(b)</span><br></pre></td></tr></table></figure>
<h3 id="对象"><a href="#对象" class="headerlink" title="对象"></a>对象</h3><ol>
<li>Python中，一切皆对象。</li>
<li>每个对象由：标识（identity）、类型（type）、value（值）组成</li>
</ol>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311102017825.png" alt="image-20231110201745676"></p>
<blockquote>
<ol>
<li>标识用于唯一标识对象，通常对应于对象在计算机内存中的地址。使用内置函数<code>id(obj)</code>可返回对象<code>obj</code>的标识。</li>
<li>类型用于表示对象存储的“数据”的类型。类型可以限制对象的取值范围以及可执行的操作。可以使用<code>type(obj)</code>获得对象的所属类型。</li>
<li>值表示对象所存储的数据的信息。使用<code>print(obj)</code>可以直接打印出值。</li>
</ol>
<p>对象的本质就是：</p>
<p>一个内存块，拥有特定的值，支持特定类型的相关操作</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">a=<span class="number">3</span></span><br><span class="line"><span class="built_in">print</span>(a)</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">id</span>(a))</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(a))</span><br><span class="line">b=<span class="string">&#x27;我爱你&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(b)</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">id</span>(b))</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(b))</span><br></pre></td></tr></table></figure>
<p><strong>内存示意图</strong></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032047703.png" alt="image-20240203204036127"></p>
<h3 id="引用"><a href="#引用" class="headerlink" title="引用"></a>引用</h3><p>在Python中，变量也称为：对象的引用(reference)。变量存储的就是对象的地址。</p>
<p>变量通过地址引用了“对象”。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032047082.png" alt="image-20240203204134853"></p>
<p>变量位于：栈内存（压栈出栈等细节，后续再介绍）。</p>
<p>对象位于：堆内存。</p>
<p>如下源代码对应的内存图：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a=<span class="number">3</span></span><br><span class="line">b=<span class="string">&quot;我爱你&quot;</span></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032048302.png" alt="image-20240203204837202"></p>
<p><strong>==Python是动态类型语言==：变量不需要显式声明类型。根据变量引用的对象，Python解释器自动确定数据类型</strong></p>
<h3 id="标识符规则"><a href="#标识符规则" class="headerlink" title="标识符规则"></a>标识符规则</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032050282.png" alt="image-20240203205008189"></p>
<p>​                            <img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311102030659.png" alt="image-20231110203017623"></p>
<h4 id="基本用法"><a href="#基本用法" class="headerlink" title="基本用法"></a>基本用法</h4><p><strong>标识符规则：用于变量、函数、类、模块等的名称。</strong>标识符有如下特定的规则：</p>
<ol>
<li><p>区分大小写。如： <code>sxt</code> 和 <code>SXT</code> 是不同的</p>
</li>
<li><p>第一个字符必须是字母、下划线。其后的字符是：字母、数字、下划线</p>
</li>
<li><p>不能使用关键字。比如： <code>if</code> 、 <code>or</code> 、 <code>while</code> 等</p>
</li>
<li><p>以<strong>双下划线</strong>开头和结尾的名称通常有特殊含义，尽量避免这种写法。比如： <code>__init__</code> 是类的构造函数</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311102031531.png" alt="image-20231110203126470"></p>
</li>
</ol>
<h4 id="Python标识符命名规则"><a href="#Python标识符命名规则" class="headerlink" title="Python标识符命名规则"></a>Python标识符命名规则</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311102034233.png" alt="image-20231110203446167"></p>
<h3 id="变量和简单赋值语句"><a href="#变量和简单赋值语句" class="headerlink" title="变量和简单赋值语句"></a>变量和简单赋值语句</h3><h4 id="变量的声明和赋值"><a href="#变量的声明和赋值" class="headerlink" title="变量的声明和赋值"></a>变量的声明和赋值</h4><p>变量的声明和赋值：用于将一个变量绑定到一个对象上，格式： <code>变量名 = 表达式</code></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032053110.png" alt="image-20240203205345804"></p>
<p>最简单的表达式就是字面量。比如： <code>a = 123</code> 。运行过程中，解释器先运行右边的表达式，生成一个代表表达式运算结果的对象；然后，将这个对象地址赋值给左边的变量。</p>
<p><strong>:warning:变量在使用前必须先被初始化（先被赋值）</strong></p>
<h4 id="删除变量和垃圾回收机制"><a href="#删除变量和垃圾回收机制" class="headerlink" title="删除变量和垃圾回收机制"></a>删除变量和垃圾回收机制</h4><ol>
<li>可以通过del语句删除不再使用的变量。</li>
<li>如果对象没有变量引用，就会被垃圾回收器回收，清空内存空间。</li>
</ol>
<p>【操作】删除变量示例</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a=<span class="number">123</span></span><br><span class="line"><span class="keyword">del</span> a</span><br><span class="line"><span class="built_in">print</span>(a)</span><br></pre></td></tr></table></figure>
<p>报错如下：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402032056679.png" alt="image-20240203205612487"></p>
<h4 id="常量"><a href="#常量" class="headerlink" title="常量"></a>常量</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041301565.png" alt="image-20240204130134606"></p>
<p>Python不支持常量，即没有语法规则限制改变一个常量的值。我们只能约定常量的命名规则，以及在程序的逻辑上不对常量的值作出修改。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">MAX_SPEED = <span class="number">120</span></span><br><span class="line"><span class="built_in">print</span>(MAX_SPEED)  <span class="comment"># 输出120</span></span><br><span class="line">MAX_SPEED = <span class="number">140</span>   <span class="comment"># 实际是可以改的。只能逻辑上不做修改。</span></span><br><span class="line"><span class="built_in">print</span>(MAX_SPEED)  <span class="comment"># 输出140</span></span><br></pre></td></tr></table></figure>
<h4 id="链式赋值"><a href="#链式赋值" class="headerlink" title="链式赋值"></a>链式赋值</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311102047432.png" alt="image-20231110204725378"></p>
<h4 id="系列解包赋值"><a href="#系列解包赋值" class="headerlink" title="系列解包赋值"></a>系列解包赋值</h4><p>系列数据赋值给对应相同个数的变量（个数必须保持一致）</p>
<p><code>a,b,c=4,5,6</code> 相当于： <code>a=4;b=5;c=6</code></p>
<p>【操作】使用系列解包赋值实现变量值交换</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a,b=<span class="number">1</span>,<span class="number">2</span></span><br><span class="line">a,b=b,a  <span class="comment"># 变量值互换</span></span><br><span class="line"><span class="built_in">print</span>(a,b)</span><br></pre></td></tr></table></figure>
<p><strong>使用系列解包复制可以轻松实现变量值交换</strong></p>
<h3 id="最基本内置数据类型"><a href="#最基本内置数据类型" class="headerlink" title="最基本内置数据类型"></a>最基本内置数据类型</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311102103657.png" alt="image-20231110210320597"></p>
<p>python中变量没有类型，但是对象都有类型，python中最基本的内置数据类型：</p>
<ol>
<li><p>整型 <code>int</code></p>
<p>整数， 2345 , 10 , 50</p>
</li>
<li><p>浮点型 <code>float</code></p>
<p>小数， 3.14 或者科学计数法 314e-2</p>
</li>
<li><p>布尔型 <code>bool</code></p>
<p>表示真假，仅包含： True 、 False</p>
</li>
<li><p>字符串型 <code>str</code></p>
</li>
</ol>
<p>由字符组成的序列。 “abc” , ‘sxt’ , “尚学堂” , “百战程序员”</p>
<h4 id="数字和基本运算符"><a href="#数字和基本运算符" class="headerlink" title="数字和基本运算符"></a>数字和基本运算符</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311102105449.png" alt="image-20231110210508378"></p>
<h4 id="整数"><a href="#整数" class="headerlink" title="整数"></a>整数</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041252516.png" alt="image-20240204123731238"></p>
<p>==<strong>Python的整数可以无限大，任意大</strong>==</p>
<h5 id="三种进制"><a href="#三种进制" class="headerlink" title="三种进制"></a>三种进制</h5><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311102107064.png" alt="image-20231110210750024"></p>
<h5 id="使用int-实现类型转换"><a href="#使用int-实现类型转换" class="headerlink" title="使用int()实现类型转换"></a>使用int()实现类型转换</h5><ol>
<li>浮点数直接舍去小数部分。如： <code>int(9.9)</code> 结果是： <code>9</code></li>
<li>布尔值 <code>True</code> 转为 <code>1</code> ， <code>False</code> 转为 <code>0</code> 。 如： i<code>nt(True)</code> 结果是 <code>1</code></li>
<li>字符串符合整数格式（浮点数格式不行）则直接转成对应整数，否则报错</li>
</ol>
<h5 id="自动转型"><a href="#自动转型" class="headerlink" title="自动转型"></a>自动转型</h5><p>整数和浮点数混合运算时，表达式结果自动转型成浮点数。比如： <code>2+8.0</code> 的结果是 <code>10.0</code></p>
<h5 id="整数可以任意大"><a href="#整数可以任意大" class="headerlink" title="整数可以任意大"></a>整数可以任意大</h5><p>Python2中， <code>int</code> 是32位，可以存储从 <code>-2147483648</code> 到 <code>2147483647</code> 的整数（约±21亿）。Long类型是64位，可以存储：-2^63—2^63-1之间的数值。</p>
<p>Python3中， <code>int</code> 可以存储任意大小的整数， <code>long</code> 被取消。</p>
<blockquote>
<p>Python3中可以做超大数的计算，而不会造成“整数溢出”，这也是Python特别适合科学运算的特点</p>
</blockquote>
<h4 id="浮点数-float"><a href="#浮点数-float" class="headerlink" title="浮点数 float"></a>浮点数 float</h4><ol>
<li>浮点数用科学计数法表示。比如： <code>3.14</code> ，表示成： <code>314E-2</code> 或者 <code>314e-2</code></li>
<li>这些数字在内存中也是按照科学计数法存储。</li>
</ol>
<h4 id="类型转换和四舍五入"><a href="#类型转换和四舍五入" class="headerlink" title="类型转换和四舍五入"></a>类型转换和四舍五入</h4><ol>
<li>类似于 <code>int()</code> ，我们也可以使用 <code>float()</code> 将其他类型转化成浮点数。</li>
<li>整数和浮点数混合运算时，表达式结果自动转型成浮点数。比如： <code>2+8.0</code> 的结果是 <code>10.0</code></li>
<li><code>round(value)</code> 可以返回四舍五入的值。但不会改变原有值，而是产生新的值</li>
</ol>
<p>==<strong>round(value))</strong>可以返回<strong>四舍五入</strong>的值==。但<strong>不会改变原有值</strong>，而是产生新的值</p>
<h4 id="增强型赋值运算符"><a href="#增强型赋值运算符" class="headerlink" title="增强型赋值运算符"></a>增强型赋值运算符</h4><p>运算符 <code>+</code> 、 <code>-</code> 、 <code>*</code> ， <code>/</code> 、 <code>//</code> 、 <code>**</code> 和 <code>%</code> 和赋值符 <code>=</code> 结合可以构成“增强型赋值运算符”。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041251690.png" alt="image-20240204124421151"></p>
<blockquote>
<p>:warning:注意：</p>
<ol>
<li>“+=”中间不能加空格！</li>
<li>结合的是右侧整个表达式：</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">y *= x+<span class="number">2</span>  <span class="comment"># 相当于：y = y*(x+2)  而不是：y = y*x+2</span></span><br></pre></td></tr></table></figure>
</blockquote>
<h4 id="时间的表示"><a href="#时间的表示" class="headerlink" title="时间的表示"></a>时间的表示</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311102121561.png" alt="image-20231110212157494"></p>
<p>python中可以通过<code>time.time()</code> 获得当前时刻，返回的值是以秒为单位，带微秒（1/1000毫秒）精度的浮点值。例如：1635063628.5632517</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> time</span><br><span class="line">b = <span class="built_in">int</span>(time.time())</span><br><span class="line">totalMinutes = b//<span class="number">60</span></span><br><span class="line">totalHours = totalMinutes//<span class="number">60</span></span><br><span class="line">totalDays = totalHours//<span class="number">24</span></span><br><span class="line">totalYears = totalDays//<span class="number">365</span>  <span class="comment">#忽略闰年情况</span></span><br></pre></td></tr></table></figure>
<h4 id="布尔值"><a href="#布尔值" class="headerlink" title="布尔值"></a>布尔值</h4><p>Python2中没有布尔值，直接用数字 <code>0</code> 表示 <code>False</code> , 用数字 <code>1</code> 表示<code>True</code> 。</p>
<p>Python3中，把 <code>True</code> 和 <code>False</code> 定义成了关键字，但他们的本质还是 <code>1</code> 和<code>0</code> ，甚至可以和数字相加。</p>
<blockquote>
<p>在Python语言底层，会将布尔值<code>True</code>看作<code>1</code>，将布尔值<code>False</code>看作<code>0</code>，尽管从表面上看，<code>True</code>和<code>1</code>、<code>False</code>和<code>0</code>是完全不同的两个值，但实际上，它们是相同的。</p>
<p>在Python语言中有一些特殊的布尔类型值为<code>False</code>，例如False、0、0.0、空值None、空序列对象（空列表、空元祖、空集合、空字典、空字符串）、空range对象、空迭代对象。其他情况，均为True。</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="literal">True</span></span><br><span class="line">b = <span class="number">3</span></span><br><span class="line">c = a+b <span class="comment">#c的值是：4</span></span><br><span class="line"><span class="built_in">print</span>(c)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;空字符串的布尔类型的值:&#x27;</span>,<span class="built_in">bool</span>(<span class="string">&quot;&quot;</span>)) </span><br><span class="line"><span class="comment">#False</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;空列表布尔类型的值:&#x27;</span>,<span class="built_in">bool</span>([])) </span><br><span class="line"><span class="comment">#False</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;None布尔类型的值:&#x27;</span>,<span class="built_in">bool</span>(<span class="literal">None</span>)) </span><br><span class="line"><span class="comment">#False</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;0布尔类型的值:&#x27;</span>,<span class="built_in">bool</span>(<span class="number">0</span>)) </span><br><span class="line"><span class="comment">#False</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;字符串True和False转成布尔都是True：&#x27;</span>,<span class="built_in">bool</span>(<span class="string">&quot;False&quot;</span>)) </span><br><span class="line"><span class="comment">#True</span></span><br></pre></td></tr></table></figure>
<h3 id="运算符"><a href="#运算符" class="headerlink" title="运算符"></a>运算符</h3><h4 id="逻辑运算符"><a href="#逻辑运算符" class="headerlink" title="逻辑运算符"></a>逻辑运算符</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041251409.png" alt="image-20240204125036900"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#测试逻辑运算符</span></span><br><span class="line">a,b,c=<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span></span><br><span class="line"><span class="built_in">print</span>((a&lt;b) <span class="keyword">and</span> (b&lt;c))   <span class="comment"># and并且  输出结果是True</span></span><br><span class="line"><span class="built_in">print</span>((a&gt;b) <span class="keyword">or</span> (b&gt;c))    <span class="comment"># or或者   输出结果是False</span></span><br><span class="line"><span class="built_in">print</span>(<span class="keyword">not</span>(b&lt;c))          <span class="comment"># not非    输出结果是False</span></span><br></pre></td></tr></table></figure>
<h4 id="比较运算符"><a href="#比较运算符" class="headerlink" title="比较运算符"></a>比较运算符</h4><p>所有比较运算符返回 <code>1</code> 表示真，返回 <code>0</code> 表示假。这分别与特殊变量<code>True</code> 和 <code>False</code> 等价。</p>
<p>以下假设变量 a为15 ，变量 b为30 ：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041253265.png" alt="image-20240204125302905"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="number">4</span></span><br><span class="line"><span class="built_in">print</span>(a&lt;=<span class="number">30</span>)</span><br><span class="line"><span class="comment"># 关系运算符可以连用</span></span><br><span class="line"><span class="keyword">if</span>(<span class="number">3</span>&lt;a&lt;<span class="number">10</span>):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;a在3和10之间&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><strong>关系运算符可以连用   如： <code>2&lt;a&lt;10</code></strong></p>
<h4 id="位运算符"><a href="#位运算符" class="headerlink" title="位运算符"></a>位运算符</h4><p>按位运算符是把数字看作二进制来进行计算的。Python中的按位运算法则如表所示。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041254246.png" alt="image-20240204125414233"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="number">0b11001</span></span><br><span class="line">b = <span class="number">0b01000</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">bin</span>(a|b))   <span class="comment"># bin()可以将数字转成二进制表示&#x27;0b11001&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">bin</span>(a&amp;b))   <span class="comment"># 与</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">bin</span>(a^b))   <span class="comment"># 异或</span></span><br><span class="line"><span class="built_in">print</span>(<span class="number">3</span>&lt;&lt;<span class="number">2</span>)       <span class="comment"># 左移1位相当于乘以2.左移两位相当于：3*4</span></span><br><span class="line"><span class="built_in">print</span>(<span class="number">20</span>&gt;&gt;<span class="number">1</span>)      <span class="comment"># 右移移位相当于除以2</span></span><br></pre></td></tr></table></figure>
<h4 id="加法操作补充"><a href="#加法操作补充" class="headerlink" title="加法操作补充"></a>加法操作补充</h4><ol>
<li>数字相加 <code>3+2</code> 结果是 <code>5</code></li>
<li>字符串拼接 <code>&quot;3&quot;+&quot;2&quot;</code> 结果是 <code>&quot;2&quot;</code></li>
<li>列表、元组等合并 <code>[10,20,30]+[5,10,100]</code> 结果是 <code>[10,20,30,5,10,100]</code></li>
</ol>
<h4 id="乘法操作补充"><a href="#乘法操作补充" class="headerlink" title="乘法操作补充"></a>乘法操作补充</h4><ol>
<li>数字相乘 <code>3*2</code> 结果是 <code>6</code></li>
<li>字符串复制 <code>&quot;sxt&quot; * 3</code> 结果是 <code>&quot;sxtsxtsxt&quot;</code></li>
<li>列表、元组等复制 <code>[10,20,30] * 3</code> 结果是 <code>[10,20,30,10,20,30,10,20,30]</code></li>
</ol>
<p><strong>字符串拼接 <code>&quot;3&quot;+&quot;4&quot;</code>   结果 <code>&quot;34&quot;</code></strong></p>
<p><strong>列表，元组等合并  <code>[1,2,3]+[4,5,6]</code>   结果  <code>[1,2,3,4,5,6]</code></strong></p>
<p><strong>字符串复制  <code>&quot;abc&quot;* 3</code>     结果  <code>&quot;abcabcabc&quot;</code></strong></p>
<p><strong>列表，元组等复制  <code>[1,2,3] * 3</code>     结果 <code>[1,2,3,1,2,3,1,2,3]</code></strong></p>
<h4 id="增强赋值运算符-补充"><a href="#增强赋值运算符-补充" class="headerlink" title="增强赋值运算符(补充)"></a>增强赋值运算符(补充)</h4><p>复合赋值可以让程序更加精炼，提高效率。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041307799.png" alt="image-20240204130748779"></p>
<p>:warning:<strong>与C和JAVA不一样，Python不支持自增(++)和自减(—)</strong></p>
<h4 id="同一运算符"><a href="#同一运算符" class="headerlink" title="同一运算符"></a>同一运算符</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041309778.png" alt="image-20240204130917419"></p>
<p>同一运算符用于比较两个对象的存储单元，实际比较的是对象的地址。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041309937.png" alt="image-20240204130945916"></p>
<p><code>is</code> 与 <code>==</code> 区别：</p>
<ol>
<li><code>is</code> 用于判断两个变量引用对象是否为同一个，既比较对象的地址。</li>
<li><code>==</code> 用于判断引用变量引用对象的值是否相等，默认调用对象的<code>__eq__()</code> 方法。</li>
</ol>
<blockquote>
<p>总结</p>
<ol>
<li><code>is</code> 比较两个对象的 <code>id</code> 值是否相等，是否指向同一个内存地址 </li>
<li><code>==</code> 比较的是两个对象的内容是否相等，值是否相等 </li>
<li><code>is</code> 运算符比 <code>==</code> 效率高，在变量和 <code>None</code> 进行比较时，应该使用 <code>is</code></li>
</ol>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">a=<span class="number">20</span></span><br><span class="line">b=<span class="number">20</span></span><br><span class="line">c=<span class="number">30</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;a和b是同一个对象&quot;</span>,a <span class="keyword">is</span> b)   <span class="comment"># 执行结果:True</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;a和c是同一个对象&quot;</span>,a <span class="keyword">is</span> c)   <span class="comment"># 执行结果False</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;a和c不是同一个对象&quot;</span>,a <span class="keyword">is</span> <span class="keyword">not</span> c)   <span class="comment"># 执行结果True</span></span><br></pre></td></tr></table></figure>
<p>【操作】同一运算符测试</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="number">1000</span></span><br><span class="line">b = <span class="number">1000</span></span><br><span class="line">a == b   <span class="comment"># True</span></span><br><span class="line">a <span class="keyword">is</span> b   <span class="comment"># 命令行下是False。 文件下执行是True</span></span><br><span class="line">c = <span class="number">10</span></span><br><span class="line">d = <span class="number">10</span></span><br><span class="line">c <span class="keyword">is</span> d   <span class="comment"># True</span></span><br></pre></td></tr></table></figure>
<h4 id="整数缓存问题"><a href="#整数缓存问题" class="headerlink" title="整数缓存问题"></a>整数缓存问题</h4><ol>
<li>命令行模式下，Python仅仅对比较小的整数对象进行缓存（范围为<code>[-5, 256]</code>）缓存起来 <code>[C语言底层用数组实现，连续分配空间，便于查找 ]</code>，而并非是所有整数对象。</li>
<li>文件模式下，所有数字都会被缓存，范围是：<code>[-无穷大,+无穷大]</code></li>
<li>缓存实现：<code>[-5,256]</code>仍然底层用数组实现 ；不在<code>[-5,256]</code>出现的数，缓存到链表中，不连续分配空间 。</li>
</ol>
<h4 id="成员运算符"><a href="#成员运算符" class="headerlink" title="成员运算符"></a>成员运算符</h4><p>成员运算符测试实例中包含了一系列的成员，包括字符串，列表或元组。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041316334.png" alt="image-20240204131629913"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="string">&quot;python&quot;</span></span><br><span class="line">b = <span class="string">&quot;py&quot;</span></span><br><span class="line"><span class="built_in">print</span>(b <span class="keyword">in</span> a)        <span class="comment">#True</span></span><br><span class="line">c = [<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>]</span><br><span class="line"><span class="built_in">print</span>(<span class="number">10</span> <span class="keyword">not</span> <span class="keyword">in</span> c)   <span class="comment">#False</span></span><br></pre></td></tr></table></figure>
<h4 id="运算符优先级问题"><a href="#运算符优先级问题" class="headerlink" title="运算符优先级问题"></a>运算符优先级问题</h4><p>如下优先级，从高到低。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041317138.png" alt="image-20240204131751402"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#测试运算符优先级</span></span><br><span class="line">a,b,c,d=<span class="number">20</span>,<span class="number">10</span>,<span class="number">15</span>,<span class="number">5</span></span><br><span class="line">e=(a+b)*c/d        <span class="comment"># 30*15/5</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;(a+b)*c/d的执行结果:&#x27;</span>,e)</span><br><span class="line">e=(a+b)*(c/d)      <span class="comment"># 30*(15/5)</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;(a+b)*(c/d)的执行结果：&#x27;</span>,e)</span><br><span class="line">e=a+(b*c)/d        <span class="comment"># 20+150/5</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;a+(b*c)/d的执行结果：&#x27;</span>,e)</span><br></pre></td></tr></table></figure>
<p>实际使用中，记住如下简单的规则即可，复杂的表达式一定要使用小括号组织。</p>
<ol>
<li><strong>乘除优先加减</strong></li>
<li><strong>位运算和算术运算&gt;比较运算符&gt;赋值运算符&gt;逻辑运算符</strong></li>
</ol>
<h4 id="基本运算符总结"><a href="#基本运算符总结" class="headerlink" title="基本运算符总结"></a>基本运算符总结</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041319806.png" alt="image-20240204131948004"></p>
<h2 id="序列"><a href="#序列" class="headerlink" title="序列"></a>序列</h2><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311141608618.png" alt="image-20231112203832984"></p>
<h3 id="序列的本质和内存结构"><a href="#序列的本质和内存结构" class="headerlink" title="序列的本质和内存结构"></a>序列的本质和内存结构</h3><p>序列是一种数据存储方式，用来存储一系列的数据。在内存中，序列就是一块用来存放多个值的连续的内存空间。比如一个整数序列<code>[10,20,30,40]</code>，示意表示：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202405192302232.png" alt="image-20240204132820099"></p>
<p>由于Python3中一切皆对象，在内存中实际是按照如下方式存储的：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202405192302234.png" alt="image-20240204132839057"></p>
<p>==序列中存储的是整数对象的地址，而不是整数对象的值==</p>
<h3 id="字符串"><a href="#字符串" class="headerlink" title="字符串"></a>字符串</h3><h4 id="字符串基本特点"><a href="#字符串基本特点" class="headerlink" title="字符串基本特点"></a>字符串基本特点</h4><ol>
<li>字符串的本质是：字符序列。</li>
<li>Python<strong>不支持单字符类型</strong>，单字符也是作为一个字符串使用的。</li>
</ol>
<blockquote>
<p>:warning:Python的==字符串是不可变的==，我们无法对原字符串做任何修改。但，可以将字符串的一部分复制到新创建的字符串，达到“看起来修改”的效果。</p>
</blockquote>
<h4 id="字符串的编码"><a href="#字符串的编码" class="headerlink" title="字符串的编码"></a>字符串的编码</h4><p>Python3直接支持Unicode，可以表示世界上任何书面语言的字符。Python3的字符默认就是16位Unicode编码，ASCII码是Unicode编码的子集。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202405192302235.png" alt="image-20240204133145422"></p>
<p>使用内置函数ord()可以把字符转换成对应的Unicode码；</p>
<p>使用内置函数chr()可以把十进制数字转换成对应的字符。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">ord</span>(<span class="string">&#x27;A&#x27;</span>)  <span class="comment">#65</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">ord</span>(<span class="string">&#x27;高&#x27;</span>) <span class="comment">#39640</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">chr</span>(<span class="number">66</span>)   <span class="comment">#&#x27;B&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">ord</span>(<span class="string">&#x27;淇&#x27;</span>) <span class="comment">#28103</span></span><br></pre></td></tr></table></figure>
<h4 id="引号创建字符串"><a href="#引号创建字符串" class="headerlink" title="引号创建字符串"></a>引号创建字符串</h4><p>我们可以通过<strong>单引号</strong>或<strong>双引号</strong>创建字符串。例如： <code>a=&#39;abc&#39;</code> <code>b=&quot;sxt&quot;</code></p>
<p>使用两种引号的好处是可以创建本身就包含引号的字符串，而不用使用转义字符。例如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="string">&quot;I&#x27;m a teacher!&quot;</span> </span><br><span class="line"><span class="built_in">print</span>(a) <span class="comment"># I&#x27;m a teacher!</span></span><br><span class="line">b = <span class="string">&#x27;my_name is &quot;TOM&quot;&#x27;</span>  </span><br><span class="line"><span class="built_in">print</span>(b) <span class="comment"># my_name is &quot;TOM&quot;</span></span><br></pre></td></tr></table></figure>
<p>连续三个单引号或三个双引号，可以帮助我们创建多行字符串。在长字符串中会保留原始的格式。例如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">s=<span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="string"> I</span></span><br><span class="line"><span class="string">   Love</span></span><br><span class="line"><span class="string">       Python</span></span><br><span class="line"><span class="string"> &#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(s)</span><br></pre></td></tr></table></figure>
<h4 id="空字符串和len-函数"><a href="#空字符串和len-函数" class="headerlink" title="空字符串和len()函数"></a>空字符串和len()函数</h4><p>Python允许空字符串的存在，不包含任何字符且长度为0。例如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">c = <span class="string">&#x27;&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">len</span>(c)) <span class="comment"># 结果：0</span></span><br></pre></td></tr></table></figure>
<p>len()用于计算字符串含有多少字符。例如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">d = <span class="string">&#x27;abc尚学堂&#x27;</span></span><br><span class="line"><span class="built_in">len</span>(d)   <span class="comment"># 结果：6</span></span><br></pre></td></tr></table></figure>
<h4 id="转义字符"><a href="#转义字符" class="headerlink" title="转义字符"></a>转义字符</h4><p>我们可以使用 +特殊字符 ，实现某些难以用字符表示的效果。比如：换行等。常见的转义字符有这些：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041336465.png" alt="image-20240204133642825"></p>
<p>【操作】测试转义字符的使用</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="string">&#x27;I\nlove\nU&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(a)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;aabb\\cc&#x27;</span>)</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">输出：</span></span><br><span class="line"><span class="string">I</span></span><br><span class="line"><span class="string">love</span></span><br><span class="line"><span class="string">U</span></span><br><span class="line"><span class="string">aabb\cc</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h4 id="字符串拼接"><a href="#字符串拼接" class="headerlink" title="字符串拼接"></a>字符串拼接</h4><ol>
<li>可以使用 <code>+</code> 将多个字符串拼接起来。例如： <code>&#39;aa&#39; +&#39;bb&#39;</code> 结果是 <code>&#39;aabb&#39;</code><ul>
<li>如果 <code>+</code> 两边都是字符串，则拼接。</li>
<li>如果 <code>+</code> 两边都是数字，则加法运算</li>
<li>如果 <code>+</code> 两边类型不同，则抛出异常</li>
</ul>
</li>
<li>可以将多个字面字符串直接放到一起实现拼接。例如： <code>&#39;aa&#39; &#39;bb&#39;</code> 结果是 <code>&#39;aabb&#39;</code></li>
</ol>
<p>【操作】字符串拼接操作</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="string">&#x27;sxt&#x27;</span>+<span class="string">&#x27;gaoqi&#x27;</span>    <span class="comment">#结果是：&#x27;sxtgaoqi&#x27;</span></span><br><span class="line">b = <span class="string">&#x27;sxt&#x27;</span><span class="string">&#x27;gaoqi&#x27;</span>     <span class="comment">#结果是：&#x27;sxtgaoqi&#x27;</span></span><br></pre></td></tr></table></figure>
<h4 id="字符串复制"><a href="#字符串复制" class="headerlink" title="字符串复制"></a>字符串复制</h4><p>使用<code>*</code>可以实现字符串复制</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="string">&#x27;Sxt&#x27;</span>*<span class="number">3</span>    <span class="comment"># 结果:&#x27;SxtSxtSxt&#x27;</span></span><br></pre></td></tr></table></figure>
<h4 id="不换行打印"><a href="#不换行打印" class="headerlink" title="不换行打印"></a>不换行打印</h4><p>我们前面调用print时，会自动打印一个换行符。有时，我们不想换行，不想自动添加换行符。我们可以自己通过参数<code>end = &quot;任意字符串&quot;</code>。实现末尾添加任何内容：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(<span class="string">&quot;sxt&quot;</span>,end=<span class="string">&#x27; &#x27;</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;sxt&quot;</span>,end=<span class="string">&#x27;##&#x27;</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;sxt&quot;</span>)</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">sxt sxt##sxt</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h4 id="从控制台读取字符串"><a href="#从控制台读取字符串" class="headerlink" title="从控制台读取字符串"></a>从控制台读取字符串</h4><p>我们可以使用input()从控制台读取键盘输入的内容。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">myname = <span class="built_in">input</span>(<span class="string">&quot;请输入名字:&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;您的名字是：&quot;</span>+myname)</span><br></pre></td></tr></table></figure>
<h4 id="replace-实现字符串替换"><a href="#replace-实现字符串替换" class="headerlink" title="replace()实现字符串替换"></a><code>replace()</code>实现字符串替换</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041353792.png" alt="image-20240204135112227"></p>
<p>==<strong>字符串是不可变的</strong>==，我们通过[]可以获取字符串指定位置的字符，但是我们不能改变字符串。我们尝试改变字符串中某个字符，</p>
<p>发现报错了：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = <span class="string">&#x27;abcdefghijklmnopqrstuvwxyz&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a</span><br><span class="line"><span class="string">&#x27;abcdefghijklmnopqrstuvwxyz&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a[<span class="number">3</span>]=<span class="string">&#x27;高&#x27;</span></span><br><span class="line">Traceback (most recent call last):</span><br><span class="line"> File <span class="string">&quot;&lt;pyshell#94&gt;&quot;</span>, line <span class="number">1</span>, <span class="keyword">in</span> &lt;module&gt;</span><br><span class="line">   a[<span class="number">3</span>]=<span class="string">&#x27;高&#x27;</span></span><br><span class="line">TypeError: <span class="string">&#x27;str&#x27;</span> <span class="built_in">object</span> does <span class="keyword">not</span> support item</span><br><span class="line">assignment</span><br></pre></td></tr></table></figure>
<p>字符串不可改变。但是，我们确实有时候需要替换某些字符。这时，只能通过创建新的字符串来实现。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = <span class="string">&#x27;abcdefghijklmnopqrstuvwxyz&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a</span><br><span class="line"><span class="string">&#x27;abcdefghijklmnopqrstuvwxyz&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = a.replace(<span class="string">&#x27;c&#x27;</span>,<span class="string">&#x27;高&#x27;</span>)</span><br><span class="line"><span class="string">&#x27;ab高defghijklmnopqrstuvwxyz&#x27;</span></span><br></pre></td></tr></table></figure>
<p>整个过程中，实际上我们是创建了新的字符串对象，并指向了变量a，而不是修改了以前的字符串。 内存图如下：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041353792.png" alt="image-20240204135112227"></p>
<h4 id="str-实现数字转型字符串"><a href="#str-实现数字转型字符串" class="headerlink" title="str()实现数字转型字符串"></a><code>str()</code>实现数字转型字符串</h4><p>str()可以帮助我们将其他数据类型转换为字符串。例如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="built_in">str</span>(<span class="number">5.20</span>)     <span class="comment"># 结果是：a = &#x27;5.20&#x27; </span></span><br><span class="line">b = <span class="built_in">str</span>(<span class="number">3.14e2</span>)   <span class="comment"># 结果是：b = &#x27;314.0&#x27; </span></span><br><span class="line">c = <span class="built_in">str</span>(<span class="literal">True</span>)     <span class="comment"># 结果是：c = &#x27;True&#x27;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>当我们调用print()函数时，解释器自动调用了str()将非字符串的对象转成了字符串。</p>
</blockquote>
<h4 id="使用-提取字符"><a href="#使用-提取字符" class="headerlink" title="使用[]提取字符"></a>使用<code>[]</code>提取字符</h4><p>字符串的本质就是字符序列，我们可以通过在字符串后面添加<code>[]</code>，在<code>[]</code>里面指定偏移量，可以提取该位置的单个字符。</p>
<ol>
<li><p>正向搜索：</p>
<p>最左侧第一个字符，偏移量是<code>0</code>，第二个偏移量是<code>1</code>，以此类推。直到<code>len(str)-1</code>为止。</p>
</li>
<li><p>反向搜索：</p>
<p>最右侧第一个字符，偏移量是<code>-1</code>，倒数第二个偏移量是<code>-2</code>，以此类推，直到<code>-len(str)</code>为止。</p>
</li>
</ol>
<p>【操作】使用<code>[]</code>提取字符串中的字符</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = <span class="string">&#x27;abcdefghijklmnopqrstuvwxyz&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a</span><br><span class="line"><span class="string">&#x27;abcdefghijklmnopqrstuvwxyz&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a[<span class="number">0</span>]</span><br><span class="line"><span class="string">&#x27;a&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a[<span class="number">3</span>]</span><br><span class="line"><span class="string">&#x27;d&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a[<span class="number">26</span>-<span class="number">1</span>]</span><br><span class="line"><span class="string">&#x27;z&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a[-<span class="number">1</span>]</span><br><span class="line"><span class="string">&#x27;z&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a[-<span class="number">26</span>]</span><br><span class="line"><span class="string">&#x27;a&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a[-<span class="number">30</span>]</span><br><span class="line">Traceback (most recent call last):</span><br><span class="line"> File <span class="string">&quot;&lt;pyshell#91&gt;&quot;</span>, line <span class="number">1</span>, <span class="keyword">in</span> &lt;module&gt;</span><br><span class="line">   a[-<span class="number">30</span>]</span><br><span class="line">IndexError: string index out of <span class="built_in">range</span></span><br></pre></td></tr></table></figure>
<h4 id="字符串切片slice操作"><a href="#字符串切片slice操作" class="headerlink" title="字符串切片slice操作"></a>字符串切片<code>slice</code>操作</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041400465.png" alt="image-20240204135915541"></p>
<p>切片slice操作可以让我们快速的提取子字符串。标准格式为：</p>
<p><code>[起始偏移量start: 终止偏移量end: 步长step]</code></p>
<p>典型操作(三个量为正数的情况)如下：==包头不包尾==</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041402249.png" alt="image-20240204140041462"></p>
<p>其他操作（三个量为负数）的情况：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041401188.png" alt="image-20240204140151411"></p>
<p><strong>字符串逆序  <code>[::-1]</code></strong></p>
<p>切片操作时，起始偏移量和终止偏移量不在<code>[0,字符串长度-1]</code>这个范围，也不会报错。<strong>起始偏移量小于0则会当做0</strong>，<strong>终止偏移量大于“长度-1”会被当成-1</strong>。例如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">&quot;abcdefg&quot;</span>[<span class="number">3</span>:<span class="number">50</span>]</span><br><span class="line"><span class="string">&#x27;defg&#x27;</span></span><br></pre></td></tr></table></figure>
<p>我们发现正常输出了结果，没有报错。</p>
<h4 id="split-分割和join-合并"><a href="#split-分割和join-合并" class="headerlink" title="split()分割和join()合并"></a><code>split()</code>分割和<code>join()</code>合并</h4><p><code>split()</code>可以基于指定分隔符将字符串分隔成多个子字符串(存储到列表中)。如果不指定分隔符，则<strong>默认使用空白字符</strong>(换行符/空格/制表符)。示例代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = <span class="string">&quot;to be or not to be&quot;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.split()</span><br><span class="line">[<span class="string">&#x27;to&#x27;</span>, <span class="string">&#x27;be&#x27;</span>, <span class="string">&#x27;or&#x27;</span>, <span class="string">&#x27;not&#x27;</span>, <span class="string">&#x27;to&#x27;</span>, <span class="string">&#x27;be&#x27;</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.split(<span class="string">&#x27;be&#x27;</span>)</span><br><span class="line">[<span class="string">&#x27;to &#x27;</span>, <span class="string">&#x27; or not to &#x27;</span>, <span class="string">&#x27;&#x27;</span>]</span><br></pre></td></tr></table></figure>
<p><code>join()</code>的作用和<code>split()</code>作用刚好相反，用于将一系列子字符串连接起来。示例代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = [<span class="string">&#x27;sxt&#x27;</span>,<span class="string">&#x27;sxt100&#x27;</span>,<span class="string">&#x27;sxt200&#x27;</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">&#x27;*&#x27;</span>.join(a)</span><br><span class="line"><span class="string">&#x27;sxt*sxt100*sxt200&#x27;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>拼接字符串要点：</p>
<p> 使用字符串拼接符 <code>+</code> ，会生成新的字符串对象，因此==不推荐使用 <code>+</code> 来拼接字符串==。==推荐使用 <code>join</code> 函数==，因为 <code>join</code> 函数在拼接字符串之前会计算所有字符串的长度，然后逐一拷贝，仅新建一次对象。</p>
</blockquote>
<p>==<strong>join拼接字符串效率高</strong>==</p>
<h4 id="字符串驻留机制"><a href="#字符串驻留机制" class="headerlink" title="字符串驻留机制"></a>字符串驻留机制</h4><p><strong>字符串驻留：常量字符串只保留一次</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">c = <span class="string">&quot;dd#&quot;</span></span><br><span class="line">d = <span class="string">&quot;dd#&quot;</span></span><br><span class="line"><span class="built_in">print</span>(c <span class="keyword">is</span> d)   <span class="comment">#True</span></span><br></pre></td></tr></table></figure>
<h4 id="字符串比较和同一性"><a href="#字符串比较和同一性" class="headerlink" title="字符串比较和同一性"></a>字符串比较和同一性</h4><p>我们可以直接使用 <code>==</code> <code>!=</code> 对字符串进行比较，<strong>是否含有相同的字符</strong>。</p>
<p>我们使用 <code>is</code> <code>not is</code> ，判断两个对象<strong>是否同一个对象</strong>。比较的是对象的地址，即 <code>id(obj1)</code> 是否和 <code>id(obj2)</code> 相等。</p>
<p><strong>== 和!=比较是否含有相同字符</strong></p>
<p><strong>is和not is判断是否同一对象</strong></p>
<h4 id="成员操作符判断子字符串"><a href="#成员操作符判断子字符串" class="headerlink" title="成员操作符判断子字符串"></a>成员操作符判断子字符串</h4><p><code>in</code> <code>not in</code> 关键字，判断某个字符(子字符串)是否存在于字符串中。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;ab&quot;</span> <span class="keyword">in</span> <span class="string">&quot;abcdefg&quot;</span>     <span class="comment">#true</span></span><br></pre></td></tr></table></figure>
<h4 id="字符串常用方法汇总"><a href="#字符串常用方法汇总" class="headerlink" title="字符串常用方法汇总"></a>字符串常用方法汇总</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041410134.png" alt="image-20240204141005422"></p>
<h5 id="常用查找方法"><a href="#常用查找方法" class="headerlink" title="常用查找方法"></a>常用查找方法</h5><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041410765.png" alt="image-20240204141055893"></p>
<h5 id="去除首尾信息"><a href="#去除首尾信息" class="headerlink" title="去除首尾信息"></a>去除首尾信息</h5><p>我们可以通过<code>strip()</code>去除字符串<strong>首尾</strong>指定信息。通过<code>lstrip()</code>去除字符串<strong>左边</strong>指定信息，<code>rstrip()</code>去除字符串<strong>右边</strong>指定信息。</p>
<p>【操作】去除字符串首尾信息</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">&quot;*s*x*t*&quot;</span>.strip(<span class="string">&quot;*&quot;</span>)</span><br><span class="line"><span class="string">&#x27;s*x*t&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">&quot;*s*x*t*&quot;</span>.lstrip(<span class="string">&quot;*&quot;</span>)</span><br><span class="line"><span class="string">&#x27;s*x*t*&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">&quot;*s*x*t*&quot;</span>.rstrip(<span class="string">&quot;*&quot;</span>)</span><br><span class="line"><span class="string">&#x27;*s*x*t&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">&quot; s xt &quot;</span>.strip()</span><br><span class="line"><span class="string">&#x27;s xt&#x27;</span></span><br></pre></td></tr></table></figure>
<h5 id="大小写转换"><a href="#大小写转换" class="headerlink" title="大小写转换"></a>大小写转换</h5><p>编程中关于字符串大小写转换的情况，经常遇到。我们将相关方法汇总到这里。为了方便学习，先设定一个测试变量：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="string">&quot;gaoqi love programming, love SXT&quot;</span></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041413926.png" alt="image-20240204141327484"></p>
<h5 id="格式排版"><a href="#格式排版" class="headerlink" title="格式排版"></a>格式排版</h5><p><code>center()</code> 、 <code>ljust()</code> 、 <code>rjust()</code> 这三个函数用于对字符串实现排版。示例如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a=<span class="string">&quot;SXT&quot;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.center(<span class="number">10</span>,<span class="string">&quot;*&quot;</span>)</span><br><span class="line"><span class="string">&#x27;***SXT****&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.center(<span class="number">10</span>)</span><br><span class="line"><span class="string">&#x27;   SXT   &#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.ljust(<span class="number">10</span>,<span class="string">&quot;*&quot;</span>)</span><br><span class="line"><span class="string">&#x27;SXT*******&#x27;</span></span><br></pre></td></tr></table></figure>
<h5 id="特征判断方法"><a href="#特征判断方法" class="headerlink" title="特征判断方法"></a>特征判断方法</h5><ol>
<li>isalnum() 是否为字母或数字</li>
<li>isalpha() 检测字符串是否只由字母组成(含汉字)</li>
<li>isdigit() 检测字符串是否只由数字组成</li>
<li>isspace()检测是否为空白符</li>
<li>isupper() 是否为大写字母</li>
<li>islower() 是否为小写字母</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">&quot;sxt100&quot;</span>.isalnum()</span><br><span class="line"><span class="literal">True</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">&quot;sxt尚学堂&quot;</span>.isalpha()</span><br><span class="line"><span class="literal">True</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">&quot;234.3&quot;</span>.isdigit()</span><br><span class="line"><span class="literal">False</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">&quot;23423&quot;</span>.isdigit()</span><br><span class="line"><span class="literal">True</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">&quot;aB&quot;</span>.isupper()</span><br><span class="line"><span class="literal">False</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">&quot;A&quot;</span>.isupper()</span><br><span class="line"><span class="literal">True</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">&quot;\t\n&quot;</span>.isspace()</span><br><span class="line"><span class="literal">True</span></span><br></pre></td></tr></table></figure>
<h4 id="字符串的格式化"><a href="#字符串的格式化" class="headerlink" title="字符串的格式化"></a>字符串的格式化</h4><h5 id="format-基本用法"><a href="#format-基本用法" class="headerlink" title="format() 基本用法"></a><code>format()</code> 基本用法</h5><p>基本语法是通过 <code>&#123;&#125;</code> 和 : 来代替以前的 <code>%</code> 。</p>
<p><code>format()</code> 函数可以接受不限个数的参数，位置可以不按顺序。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = <span class="string">&quot;名字是:&#123;0&#125;,年龄是：&#123;1&#125;&quot;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.<span class="built_in">format</span>(<span class="string">&quot;杰克&quot;</span>,<span class="number">18</span>)</span><br><span class="line"><span class="string">&#x27;名字是:杰克,年龄是：18&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.<span class="built_in">format</span>(<span class="string">&quot;高希希&quot;</span>,<span class="number">6</span>)</span><br><span class="line"><span class="string">&#x27;名字是:高希希,年龄是：6&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b = <span class="string">&quot;名字是：&#123;0&#125;，年龄是&#123;1&#125;。&#123;0&#125;是个好小伙&quot;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b.<span class="built_in">format</span>(<span class="string">&quot;杰克&quot;</span>,<span class="number">18</span>)</span><br><span class="line"><span class="string">&#x27;名字是：杰克，年龄是18。杰克是个好小伙&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>c = <span class="string">&quot;名字是&#123;name&#125;，年龄是&#123;age&#125;&quot;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>c.<span class="built_in">format</span>(age=<span class="number">19</span>,name=<span class="string">&#x27;杰克&#x27;</span>)</span><br><span class="line"><span class="string">&#x27;名字是杰克，年龄是19&#x27;</span></span><br></pre></td></tr></table></figure>
<p><strong>我们可以通过{索引}/{参数名}，直接映射参数值，实现对字符串的格式化，非常方便。</strong></p>
<h5 id="填充与对齐"><a href="#填充与对齐" class="headerlink" title="填充与对齐"></a>填充与对齐</h5><ol>
<li>填充常跟对齐一起使用</li>
<li><code>^</code> 、 <code>&lt;</code> 、 <code>&gt;</code> 分别是居中、左对齐、右对齐，后面带宽度 </li>
<li><code>:</code> 号后面带填充的字符，只能是一个字符，不指定的话默认是用空格填充</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">&quot;&#123;:*&gt;8&#125;&quot;</span>.<span class="built_in">format</span>(<span class="string">&quot;245&quot;</span>)</span><br><span class="line"><span class="string">&#x27;*****245&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">&quot;我是&#123;0&#125;,我喜欢数字&#123;1:*^8&#125;&quot;</span>.<span class="built_in">format</span>(<span class="string">&quot;杰克&quot;</span>,<span class="string">&quot;666&quot;</span>)</span><br><span class="line"><span class="string">&#x27;我是杰克,我喜欢数字**666***&#x27;</span></span><br></pre></td></tr></table></figure>
<h5 id="数字格式化"><a href="#数字格式化" class="headerlink" title="数字格式化"></a>数字格式化</h5><p>浮点数通过 <code>f</code> ，整数通过 <code>d</code> 进行需要的格式化。案例如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = <span class="string">&quot;我是&#123;0&#125;，我的存款有&#123;1:.2f&#125;&quot;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.<span class="built_in">format</span>(<span class="string">&quot;高淇&quot;</span>,<span class="number">3888.234342</span>)</span><br><span class="line"><span class="string">&#x27;我是高淇，我的存款有3888.23&#x27;</span></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202405192302236.png" alt="image-20240204142036151"></p>
<h4 id="可变字符串"><a href="#可变字符串" class="headerlink" title="可变字符串"></a>可变字符串</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202405192302237.png" alt="image-20240204142108726"></p>
<ol>
<li>Python中，字符串属于不可变对象，不支持原地修改，如果需要修改其中的值，只能创建新的字符串对象。</li>
<li>确实需要原地修改字符串，可以使用<code>io.StringIO</code>对象或<code>array</code>模块</li>
</ol>
<p><strong>使用<code>io.StringIO</code>可以将字符串变为可变字符串</strong></p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> io</span><br><span class="line">s = <span class="string">&quot;hello, sxt&quot;</span></span><br><span class="line">sio = io.StringIO(s)   <span class="comment"># 可变字符串</span></span><br><span class="line"><span class="built_in">print</span>(sio)</span><br><span class="line">v1 = sio.getvalue()</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;v1:&quot;</span>,v1)</span><br><span class="line">char7 = sio.seek(<span class="number">7</span>)    <span class="comment"># 指针知道索引7这个位置</span></span><br><span class="line">sio.write(<span class="string">&quot;gaoqi&quot;</span>)</span><br><span class="line">v2 = sio.getvalue()</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;v2:&quot;</span>,v2)</span><br></pre></td></tr></table></figure>
<h4 id="类型转换总结"><a href="#类型转换总结" class="headerlink" title="类型转换总结"></a>类型转换总结</h4><p>与C++、Java等高级程序设计语言一样，Python语言同样也支持数据类型转换。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041424838.png" alt="image-20240204142410256"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#类型转换</span></span><br><span class="line"><span class="comment">#转换为int</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;int()默认情况下为：&#x27;</span>, <span class="built_in">int</span>())</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;str字符型转换为int：&#x27;</span>, <span class="built_in">int</span>(<span class="string">&#x27;010&#x27;</span>))</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;float浮点型转换为int：&#x27;</span>, <span class="built_in">int</span>(<span class="number">234.23</span>))</span><br><span class="line"><span class="comment">#十进制数10，对应的2进制，8进制，10进制，16进制分别是：1010,12,10,0xa</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;int(\&#x27;0xa\&#x27;, 16) = &#x27;</span>, <span class="built_in">int</span>(<span class="string">&#x27;0xa&#x27;</span>, <span class="number">16</span>))</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;int(\&#x27;10\&#x27;, 10) = &#x27;</span>, <span class="built_in">int</span>(<span class="string">&#x27;10&#x27;</span>, <span class="number">10</span>))</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;int(\&#x27;12\&#x27;, 8) = &#x27;</span>, <span class="built_in">int</span>(<span class="string">&#x27;12&#x27;</span>, <span class="number">8</span>))</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;int(\&#x27;1010\&#x27;, 2) = &#x27;</span>, <span class="built_in">int</span>(<span class="string">&#x27;1010&#x27;</span>, <span class="number">2</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment">#转换为float</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;float()默认情况下为：&#x27;</span>, <span class="built_in">float</span>())</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;str字符型转换为float：&#x27;</span>,</span><br><span class="line"><span class="built_in">float</span>(<span class="string">&#x27;123.01&#x27;</span>))</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;int浮点型转换为float：&#x27;</span>, <span class="built_in">float</span>(<span class="number">32</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment">#转换为complex</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;创建一个复数(实部+虚部)：&#x27;</span>, <span class="built_in">complex</span>(<span class="number">12</span>,<span class="number">43</span>))</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;创建一个复数(实部+虚部)：&#x27;</span>, <span class="built_in">complex</span>(<span class="number">12</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment">#转换为str字符串</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;str()默认情况下为：&#x27;</span>, <span class="built_in">str</span>())</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;float型转换为str：&#x27;</span>, <span class="built_in">str</span>(<span class="number">232.33</span>))</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;int转换为str：&#x27;</span>, <span class="built_in">str</span>(<span class="number">32</span>))</span><br><span class="line">lists = [<span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;e&#x27;</span>, <span class="string">&#x27;c&#x27;</span>, <span class="string">&#x27;d&#x27;</span>, <span class="string">&#x27;a&#x27;</span>]</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;列表list转换为str:&#x27;</span>, <span class="string">&#x27;&#x27;</span>.join(lists))</span><br><span class="line"></span><br><span class="line"><span class="comment">#转换为list</span></span><br><span class="line">strs = <span class="string">&#x27;hongten&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;序列strs转换为list:&#x27;</span>, <span class="built_in">list</span>(strs))</span><br><span class="line"></span><br><span class="line"><span class="comment">#转换为tuple</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;列表list转换为tuple:&#x27;</span>, <span class="built_in">tuple</span>(lists))</span><br><span class="line"></span><br><span class="line"><span class="comment">#字符和整数之间的转换</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;整数转换为字符chr:&#x27;</span>, <span class="built_in">chr</span>(<span class="number">67</span>))</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;字符chr转换为整数:&#x27;</span>, <span class="built_in">ord</span>(<span class="string">&#x27;C&#x27;</span>))</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;整数转16进制数:&#x27;</span>, <span class="built_in">hex</span>(<span class="number">12</span>))</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;整数转8进制数:&#x27;</span>, <span class="built_in">oct</span>(<span class="number">12</span>))</span><br></pre></td></tr></table></figure>
<h3 id="列表"><a href="#列表" class="headerlink" title="列表"></a>列表</h3><h4 id="列表简介"><a href="#列表简介" class="headerlink" title="列表简介"></a>列表简介</h4><ol>
<li><p>列表：用于存储<strong>任意数目、任意类型</strong>的数据集合。</p>
</li>
<li><p>列表是内置<strong>可变序列</strong>，是包含多个元素的有序连续的内存空间。列表的标准语法格式：<code>a = [10,20,30,40]</code></p>
<p>其中，10,20,30,40这些称为：列表a的<strong>元素</strong>。</p>
</li>
<li><p>列表中的元素可以各不相同，可以是任意类型。比如：<code>a = [10,20,&#39;abc&#39;,True]</code></p>
</li>
<li><p>Python的列表大小可变，根据需要随时增加或缩小。</p>
</li>
</ol>
<h4 id="列表对象的常用方法"><a href="#列表对象的常用方法" class="headerlink" title="列表对象的常用方法"></a>列表对象的常用方法</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202405192302238.png" alt="image-20240204142930427"></p>
<blockquote>
<p>字符串和列表都是序列类型，一个字符串是一个字符序列，一个列表是任何元素的序列。我们前面学习的很多字符串的方法，在列表中也有类似的用法，几乎一模一样。</p>
</blockquote>
<h4 id="创建列表的4种方式"><a href="#创建列表的4种方式" class="headerlink" title="创建列表的4种方式"></a>创建列表的4种方式</h4><h5 id="基本语法-创建"><a href="#基本语法-创建" class="headerlink" title="基本语法 []创建"></a>基本语法 <code>[]</code>创建</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">10</span>,<span class="number">20</span>,<span class="string">&#x27;gaoqi&#x27;</span>,<span class="string">&#x27;sxt&#x27;</span>]</span><br><span class="line">b = []   <span class="comment"># 创建一个空的列表对象</span></span><br><span class="line"><span class="built_in">print</span>(a)</span><br></pre></td></tr></table></figure>
<h5 id="list-创建"><a href="#list-创建" class="headerlink" title="list()创建"></a><code>list()</code>创建</h5><p>使用<code>list()</code>可以将任何可迭代的数据转化成列表。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="built_in">list</span>() <span class="comment">#创建一个空的列表对象</span></span><br><span class="line">b = <span class="built_in">list</span>(<span class="built_in">range</span>(<span class="number">10</span>))   </span><br><span class="line"><span class="comment"># 结果：[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</span></span><br><span class="line">c = <span class="built_in">list</span>(<span class="string">&quot;gaoqi,sxt&quot;</span>) </span><br><span class="line"><span class="comment"># 结果：[&#x27;g&#x27;, &#x27;a&#x27;, &#x27;o&#x27;, &#x27;q&#x27;, &#x27;i&#x27;, &#x27;,&#x27;, &#x27;s&#x27;, &#x27;x&#x27;, &#x27;t&#x27;]</span></span><br></pre></td></tr></table></figure>
<h5 id="range-创建整数列表"><a href="#range-创建整数列表" class="headerlink" title="range()创建整数列表"></a><code>range()</code>创建整数列表</h5><p><code>range()</code>可以帮助我们非常方便的创建整数列表，这在开发中及其有用。语法格式为：</p>
<p><code>range([start,] end [,step])</code></p>
<blockquote>
<p>start参数：可选，表示起始数字。默认是0</p>
<p>end参数：必选，表示结尾数字。</p>
<p>step参数：可选，表示步长，默认为1</p>
<p>:warning:python3中<code>range()</code>返回的是一个range对象，而不是列表。我们需要通过<code>list()</code>方法将其转换成列表对象。</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="built_in">list</span>(<span class="built_in">range</span>(<span class="number">3</span>,<span class="number">15</span>,<span class="number">2</span>))  <span class="comment"># 结果：[3, 5, 7, 9, 11, 13]</span></span><br><span class="line">b = <span class="built_in">list</span>(<span class="built_in">range</span>(<span class="number">15</span>,<span class="number">9</span>,-<span class="number">1</span>)) <span class="comment"># 结果：[15, 14, 13, 12, 11, 10]</span></span><br><span class="line">c = <span class="built_in">list</span>(<span class="built_in">range</span>(<span class="number">3</span>,-<span class="number">4</span>,-<span class="number">1</span>)) <span class="comment"># 结果：[3, 2, 1, 0, -1, -2, -3]</span></span><br><span class="line"><span class="built_in">print</span>(a,b,c)</span><br></pre></td></tr></table></figure>
<h5 id="推导式生成列表"><a href="#推导式生成列表" class="headerlink" title="推导式生成列表"></a>推导式生成列表</h5><p>(简介一下，重点在for循环后讲)</p>
<p>使用列表推导式可以非常方便的创建列表，在开发中经常使用。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 循环创建多个元素 [0, 2, 4, 6, 8]</span></span><br><span class="line">a = [x*<span class="number">2</span> <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">5</span>)]</span><br><span class="line"><span class="comment"># 通过if过滤元素[0, 18, 36, 54, 72, 90, 108, 126, 144, 162, 180, 198]</span></span><br><span class="line">b = [x*<span class="number">2</span> <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">100</span>) <span class="keyword">if</span> x%<span class="number">9</span>==<span class="number">0</span>]</span><br><span class="line"><span class="built_in">print</span>(a,b)</span><br></pre></td></tr></table></figure>
<h4 id="增加列表元素的5种方式"><a href="#增加列表元素的5种方式" class="headerlink" title="增加列表元素的5种方式"></a>增加列表元素的5种方式</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041438970.png" alt="image-20240204143856202"></p>
<blockquote>
<p>当列表增加和删除元素时，列表会自动进行内存管理，大大减少了程序员的负担。但这个特点涉及列表元素的大量移动，效率较低。</p>
<p>:warning:除非必要，我们一般只在列表的尾部添加元素或删除元素，这会大大提高列表的操作效率。</p>
</blockquote>
<h5 id="append-方法"><a href="#append-方法" class="headerlink" title="append()方法"></a><code>append()</code>方法</h5><p>原地修改列表对象，是真正的列表尾部添加新的元素，<strong>速度最快，推荐使用</strong>。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">20</span>,<span class="number">40</span>]</span><br><span class="line">a.append(<span class="number">80</span>)</span><br><span class="line"><span class="built_in">print</span>(a)       <span class="comment"># 结果：[20, 40, 80]</span></span><br></pre></td></tr></table></figure>
<h5 id="运算符操作"><a href="#运算符操作" class="headerlink" title="+运算符操作"></a><code>+</code>运算符操作</h5><p>并不是真正的尾部添加元素，而是创建新的列表对象；将原列表的元素和新列表的元素依次复制到新的列表对象中。这样，会涉及大量的复制操作，对于操作大量元素不建议使用。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">20</span>,<span class="number">40</span>]</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">id</span>(a))</span><br><span class="line">a = a+[<span class="number">50</span>]</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">id</span>(a))  <span class="comment"># 两次地址不一样，创建了新的对象</span></span><br></pre></td></tr></table></figure>
<p>通过如上测试，我们发现变量a的地址发生了变化。也就是创建了新的列表对象。</p>
<h5 id="extend-方法"><a href="#extend-方法" class="headerlink" title="extend()方法"></a><code>extend()</code>方法</h5><p>将目标列表的所有元素添加到本列表的尾部，属于原地操作，不创建新的列表对象。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">20</span>,<span class="number">40</span>]</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">id</span>(a))</span><br><span class="line">b = [<span class="number">50</span>,<span class="number">60</span>]</span><br><span class="line">a.extend(b)     <span class="comment"># 原对象修改</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">id</span>(a))</span><br><span class="line">a = a+b         <span class="comment"># 产生新对象</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">id</span>(a))</span><br></pre></td></tr></table></figure>
<h5 id="insert-插入元素"><a href="#insert-插入元素" class="headerlink" title="insert()插入元素"></a><code>insert()</code>插入元素</h5><p>使用 <code>insert()</code> 方法可以将指定的元素插入到列表对象的任意制定位置。这样会让插入位置后面所有的元素进行移动，会影响处理速度。涉及大量元素时，尽量避免使用。类似发生这种移动的函数还有：<code>remove()</code> 、 <code>pop()</code> 、 <code>del()</code> ，它们在删除<strong>非尾部元素</strong>时也会发生操作位置后面元素的移动。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>]</span><br><span class="line">a.insert(<span class="number">2</span>,<span class="number">100</span>)</span><br><span class="line"><span class="built_in">print</span>(a)    <span class="comment"># 结果：[10, 20, 100, 30]</span></span><br></pre></td></tr></table></figure>
<h5 id="乘法扩展"><a href="#乘法扩展" class="headerlink" title="乘法扩展"></a>乘法扩展</h5><p>使用乘法扩展列表，生成一个新列表，新列表元素是原列表元素的多次重复。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="string">&#x27;sxt&#x27;</span>,<span class="number">100</span>]</span><br><span class="line">b = a*<span class="number">3</span></span><br><span class="line"><span class="built_in">print</span>(a)  <span class="comment"># 结果：[&#x27;sxt&#x27;, 100]</span></span><br><span class="line"><span class="built_in">print</span>(b)  <span class="comment"># 结果：[&#x27;sxt&#x27;, 100, &#x27;sxt&#x27;, 100, &#x27;sxt&#x27;, 100]</span></span><br></pre></td></tr></table></figure>
<p>适用于乘法操作的，还有：字符串、元组。例如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">c = <span class="string">&#x27;sxt&#x27;</span></span><br><span class="line">d = c*<span class="number">3</span>      <span class="comment"># 结果：&#x27;sxtsxtsxt&#x27;</span></span><br></pre></td></tr></table></figure>
<h4 id="列表元素的删除"><a href="#列表元素的删除" class="headerlink" title="列表元素的删除"></a>列表元素的删除</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041737533.png" alt="image-20240204173752878"></p>
<h5 id="del-删除"><a href="#del-删除" class="headerlink" title="del 删除"></a>del 删除</h5><p>删除列表指定位置的元素。</p>
<p><strong>del()传的是索引</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">100</span>,<span class="number">200</span>,<span class="number">888</span>,<span class="number">300</span>,<span class="number">400</span>]</span><br><span class="line"><span class="keyword">del</span> a[<span class="number">2</span>]</span><br><span class="line"><span class="built_in">print</span>(a)   <span class="comment"># 结果：[100,200,300,400]</span></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041739333.png" alt="image-20240204173905654"></p>
<h5 id="pop-方法"><a href="#pop-方法" class="headerlink" title="pop()方法"></a><code>pop()</code>方法</h5><p>pop()删除并返回指定位置元素，如果未指定位置则默认操作列表最后一个元素。</p>
<p><strong>pop()传的是空或索引</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">40</span>,<span class="number">50</span>]</span><br><span class="line">b1 = a.pop()   <span class="comment"># 结果：b1=50</span></span><br><span class="line"><span class="built_in">print</span>(a,b1)    <span class="comment"># 结果：[10, 20, 30, 40] 50</span></span><br><span class="line">b2 = a.pop(<span class="number">1</span>)</span><br><span class="line"><span class="built_in">print</span>(a,b2)    <span class="comment"># 结果：[10, 30, 40],20</span></span><br></pre></td></tr></table></figure>
<h5 id="remove-方法"><a href="#remove-方法" class="headerlink" title="remove()方法"></a><code>remove()</code>方法</h5><p>删除首次出现的指定元素，若不存在该元素抛出异常。</p>
<p><strong>remove() 传的是元素</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">40</span>,<span class="number">50</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">20</span>,<span class="number">30</span>]</span><br><span class="line">a.remove(<span class="number">20</span>)   <span class="comment"># [10, 30, 40, 50, 20, 30, 20, 30]</span></span><br><span class="line">a.remove(<span class="number">100</span>)  <span class="comment"># 报错：ValueError:list.remove(x): x not in list</span></span><br></pre></td></tr></table></figure>
<h4 id="列表元素访问和计数"><a href="#列表元素访问和计数" class="headerlink" title="列表元素访问和计数"></a>列表元素访问和计数</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041743482.png" alt="image-20240204174302699"></p>
<h5 id="通过索引直接访问元素"><a href="#通过索引直接访问元素" class="headerlink" title="通过索引直接访问元素"></a>通过索引直接访问元素</h5><p>我们可以通过索引直接访问元素。索引的区间在 <code>[0, 列表长度-1]</code> 这个范围。超过这个范围则会抛出异常。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">40</span>,<span class="number">50</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">20</span>,<span class="number">30</span>]</span><br><span class="line"><span class="built_in">print</span>(a[<span class="number">2</span>])   <span class="comment"># 结果：30</span></span><br><span class="line"><span class="built_in">print</span>(a[<span class="number">10</span>])  <span class="comment"># 报错：IndexError: list index out of range</span></span><br></pre></td></tr></table></figure>
<h5 id="index-获得指定元素在列表中首次出现的索引"><a href="#index-获得指定元素在列表中首次出现的索引" class="headerlink" title="index()获得指定元素在列表中首次出现的索引"></a><code>index()</code>获得指定元素在列表中首次出现的索引</h5><p><code>index()</code> 可以获取指定元素首次出现的索引位置。语法是： <code>index(value,[start,[end]])</code> 。其中， <code>start</code> 和 <code>end</code> 指定了搜索的范围。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = [<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">40</span>,<span class="number">50</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">20</span>,<span class="number">30</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.index(<span class="number">20</span>)      <span class="comment"># 结果：1</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.index(<span class="number">20</span>,<span class="number">3</span>)    <span class="comment"># 结果：5   从索引位置3开始往后搜索的第一个20</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.index(<span class="number">30</span>,<span class="number">5</span>,<span class="number">7</span>)  <span class="comment"># 结果：6 从索引位置5到7这个区间，第一次出现30元素的位置</span></span><br></pre></td></tr></table></figure>
<h5 id="count-获得指定元素在列表中出现的次数"><a href="#count-获得指定元素在列表中出现的次数" class="headerlink" title="count()获得指定元素在列表中出现的次数"></a><code>count()</code>获得指定元素在列表中出现的次数</h5><p><code>count()</code>可以返回指定元素在列表中出现的次数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = [<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">40</span>,<span class="number">50</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">20</span>,<span class="number">30</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.count(<span class="number">20</span>)</span><br><span class="line"><span class="number">3</span></span><br></pre></td></tr></table></figure>
<h5 id="len-返回列表长度"><a href="#len-返回列表长度" class="headerlink" title="len()返回列表长度"></a><code>len()</code>返回列表长度</h5><p><code>len()</code>返回列表长度，即列表中包含元素的个数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = [<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">len</span>(a)</span><br><span class="line"><span class="number">3</span></span><br></pre></td></tr></table></figure>
<h5 id="成员资格判断"><a href="#成员资格判断" class="headerlink" title="成员资格判断"></a>成员资格判断</h5><p>判断列表中是否存在指定的元素，我们可以使用 <code>count()</code> 方法，返回0则表示不存在，返回大于0则表示存在。但是，一般我们会使用更加简洁的 <code>in</code> 关键字来判断，直接返回 <code>True</code> 或 <code>False</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = [<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">40</span>,<span class="number">50</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">20</span>,<span class="number">30</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="number">20</span> <span class="keyword">in</span> a</span><br><span class="line"><span class="literal">True</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="number">100</span> <span class="keyword">not</span> <span class="keyword">in</span> a</span><br><span class="line"><span class="literal">True</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="number">30</span> <span class="keyword">not</span> <span class="keyword">in</span> a</span><br><span class="line"><span class="literal">False</span></span><br></pre></td></tr></table></figure>
<h4 id="切片操作"><a href="#切片操作" class="headerlink" title="切片操作"></a>切片操作</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041749291.png" alt="image-20240204174901657"></p>
<blockquote>
<p>类似字符串的切片操作，对于列表的切片操作和字符串类似。</p>
</blockquote>
<p>切片是Python序列及其重要的操作，适用于列表、元组、字符串等等。</p>
<p>切片<code>slice</code>操作可以让我们快速提取子列表或修改。标准格式为：</p>
<p>​                                                        <code>[起始偏移量start:终止偏移量end[:步长step]]</code></p>
<p>==包头不包尾==</p>
<p>典型操作(三个量为正数的情况)如下：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041750596.png" alt="image-20240204175030240"></p>
<p>其他操作（三个量为负数）的情况：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202405192302239.png" alt="image-20240204175047464"></p>
<blockquote>
<p>切片操作时，起始偏移量和终止偏移量不在 <code>[0,字符串长度-1]</code> 这个范围，也不会报错。起始偏移量 小于0 则会当做 0 ，终止偏移量大于”长度-1” 会被当成 “长度-1” 。例如：<code>[10,20,30,40][1:30]</code></p>
<p>结果： [20, 30, 40]</p>
<p>我们发现正常输出了结果，没有报错。</p>
</blockquote>
<h4 id="列表的遍历"><a href="#列表的遍历" class="headerlink" title="列表的遍历"></a>列表的遍历</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">40</span>]</span><br><span class="line"><span class="keyword">for</span> obj <span class="keyword">in</span> a:    <span class="comment"># obj是临时变量名称，随意起</span></span><br><span class="line">    <span class="built_in">print</span>(obj)</span><br></pre></td></tr></table></figure>
<h5 id="复制列表所有的元素到新列表对象"><a href="#复制列表所有的元素到新列表对象" class="headerlink" title="复制列表所有的元素到新列表对象"></a>复制列表所有的元素到新列表对象</h5><blockquote>
<p>如下代码实现列表元素的复制了吗？</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">list1 = [<span class="number">30</span>,<span class="number">40</span>,<span class="number">50</span>]</span><br><span class="line">list2 = list1</span><br></pre></td></tr></table></figure>
<p>只是将list2也指向了列表对象，也就是说list2和list2持有地址值是相同的，列表对象本身的元素并没有复制。</p>
</blockquote>
<p>我们可以通过如下简单方式，实现列表元素内容的复制：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">list1 = [<span class="number">30</span>,<span class="number">40</span>,<span class="number">50</span>]</span><br><span class="line">list2 = [] + list1 <span class="comment">#生成了新列表对象</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>注：我们后面也会学习copy模块，使用浅复制或深复制实现我们的复制操作</p>
</blockquote>
<h4 id="列表排序"><a href="#列表排序" class="headerlink" title="列表排序"></a>列表排序</h4><h5 id="修改原列表，不建新列表的排序"><a href="#修改原列表，不建新列表的排序" class="headerlink" title="修改原列表，不建新列表的排序"></a>修改原列表，不建新列表的排序</h5><p>使用<code>sort()</code> </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = [<span class="number">20</span>,<span class="number">10</span>,<span class="number">30</span>,<span class="number">40</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">id</span>(a)</span><br><span class="line"><span class="number">46017416</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.sort()                <span class="comment"># 默认是升序排列</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a</span><br><span class="line">[<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>, <span class="number">40</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = [<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">40</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.sort(reverse=<span class="literal">True</span>)    <span class="comment"># 降序排列</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a</span><br><span class="line">[<span class="number">40</span>, <span class="number">30</span>, <span class="number">20</span>, <span class="number">10</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> random</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>random.shuffle(a)       <span class="comment"># 打乱顺序</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a</span><br><span class="line">[<span class="number">20</span>, <span class="number">40</span>, <span class="number">30</span>, <span class="number">10</span>]</span><br></pre></td></tr></table></figure>
<h5 id="建新列表的排序"><a href="#建新列表的排序" class="headerlink" title="建新列表的排序"></a>建新列表的排序</h5><p>我们也可以通过内置函数<code>sorted()</code>进行排序，这个方法返回新列表，<strong>不对原列表做修改</strong>。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = [<span class="number">20</span>,<span class="number">10</span>,<span class="number">30</span>,<span class="number">40</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">id</span>(a)</span><br><span class="line"><span class="number">46016008</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b = <span class="built_in">sorted</span>(a)                 <span class="comment"># 默认升序</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b</span><br><span class="line">[<span class="number">10</span>, <span class="number">20</span>, <span class="number">30</span>, <span class="number">40</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">id</span>(b)</span><br><span class="line"><span class="number">45907848</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>c = <span class="built_in">sorted</span>(a,reverse=<span class="literal">True</span>)    <span class="comment"># 降序</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>c</span><br><span class="line">[<span class="number">40</span>, <span class="number">30</span>, <span class="number">20</span>, <span class="number">10</span>]</span><br></pre></td></tr></table></figure>
<p>通过上面操作，我们可以看出，生成的列表对象b和c都是完全新的列表对象。</p>
<h5 id="reversed-返回迭代器"><a href="#reversed-返回迭代器" class="headerlink" title="reversed()返回迭代器"></a><code>reversed()</code>返回迭代器</h5><p>内置函数<code>reversed()</code>也支持进行逆序排列，与列表对象<code>reverse()</code>方法不同的是，内置函数<code>reversed()</code><strong>不对原列表做任何修改</strong>，只是返回一个逆序排列的迭代器对象。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = [<span class="number">20</span>,<span class="number">10</span>,<span class="number">30</span>,<span class="number">40</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>c = <span class="built_in">reversed</span>(a)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>c</span><br><span class="line">&lt;list_reverseiterator <span class="built_in">object</span> at <span class="number">0x0000000002BCCEB8</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">list</span>(c)</span><br><span class="line">[<span class="number">40</span>, <span class="number">30</span>, <span class="number">10</span>, <span class="number">20</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">list</span>(c)</span><br><span class="line">[]</span><br></pre></td></tr></table></figure>
<p>我们打印输出c发现提示是：<code>list_reverseiterator</code>。也就是一个迭代对象。同时，我们使用<code>list(c)</code>进行输出，发现只能使用一次。第一次输出了元素，第二次为空。那是因为迭代对象在第一次时已经遍历结束了，第二次不能再使用。</p>
<h4 id="列表相关的其他内置函数汇总"><a href="#列表相关的其他内置函数汇总" class="headerlink" title="列表相关的其他内置函数汇总"></a>列表相关的其他内置函数汇总</h4><h5 id="max和min"><a href="#max和min" class="headerlink" title="max和min"></a>max和min</h5><p>用于返回列表中最大和最小值。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = [<span class="number">3</span>,<span class="number">10</span>,<span class="number">20</span>,<span class="number">15</span>,<span class="number">9</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">max</span>(a)</span><br><span class="line"><span class="number">20</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">min</span>(a)</span><br><span class="line"><span class="number">3</span></span><br></pre></td></tr></table></figure>
<h5 id="sum"><a href="#sum" class="headerlink" title="sum"></a>sum</h5><p>对数值型列表的所有元素进行求和操作，对非数值型列表运算则会报错。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = [<span class="number">3</span>,<span class="number">10</span>,<span class="number">20</span>,<span class="number">15</span>,<span class="number">9</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">sum</span>(a)</span><br><span class="line"><span class="number">57</span></span><br></pre></td></tr></table></figure>
<h4 id="多维列表"><a href="#多维列表" class="headerlink" title="多维列表"></a>多维列表</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041801798.png" alt="image-20240204180112359"></p>
<h5 id="二维列表"><a href="#二维列表" class="headerlink" title="二维列表"></a>二维列表</h5><p>一维列表可以帮助我们存储一维、线性的数据。</p>
<p>二维列表可以帮助我们存储二维、表格的数据。例如下表的数据：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311141608660.png" alt="image-20231113221834012"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311141608662.png" alt="image-20231113221906067"></p>
<p>嵌套循环打印二维列表所有的数据：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">a = [</span><br><span class="line">		[<span class="string">&quot;高小一&quot;</span>,<span class="number">18</span>,<span class="number">30000</span>,<span class="string">&quot;北京&quot;</span>],</span><br><span class="line">		[<span class="string">&quot;高小二&quot;</span>,<span class="number">19</span>,<span class="number">20000</span>,<span class="string">&quot;上海&quot;</span>],</span><br><span class="line">		[<span class="string">&quot;高小一&quot;</span>,<span class="number">20</span>,<span class="number">10000</span>,<span class="string">&quot;深圳&quot;</span>],</span><br><span class="line">	]</span><br><span class="line"><span class="keyword">for</span> m <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">3</span>):</span><br><span class="line">	<span class="keyword">for</span> n <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">4</span>):</span><br><span class="line">        <span class="built_in">print</span>(a[m][n],end=<span class="string">&quot;\t&quot;</span>)</span><br><span class="line">	<span class="built_in">print</span>() <span class="comment">#打印完一行，换行</span></span><br></pre></td></tr></table></figure>
<h3 id="元组tuple"><a href="#元组tuple" class="headerlink" title="元组tuple"></a>元组tuple</h3><p>==元组不可变序列，不能修改元组中的元素==</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041804362.png" alt="image-20240204180418518"></p>
<ul>
<li><strong>列表属于可变序列</strong>，可以任意修改列表中的元素。</li>
<li><strong>元组属于不可变序列</strong>，不能修改元组中的元素。</li>
</ul>
<p>因此，元组没有增加元素、修改元素、删除元素相关的方法。</p>
<p>因此，我们只需学元组的创建和删除，元素的访问和计数即可。元组支持如下操作：</p>
<ol>
<li>索引访问</li>
<li>切片操作</li>
<li>连接操作</li>
<li>成员关系操作</li>
<li>比较运算操作</li>
<li>计数：元组长度<code>len()</code>、最大值<code>max()</code>、最小值<code>min()</code>、求和<code>sum()</code>等</li>
</ol>
<h4 id="元组的创建"><a href="#元组的创建" class="headerlink" title="元组的创建"></a>元组的创建</h4><h5 id="通过-创建元组"><a href="#通过-创建元组" class="headerlink" title="通过()创建元组"></a>通过()创建元组</h5><p>小括号可以省略。</p>
<p><code>a = (10,20,30) 或者 a = 10,20,30</code></p>
<p>==如果元组只有一个元素，则必须后面加逗号==。这是因为解释器会把<code>(1)</code>解释为整数<code>1</code>，<code>(1,)</code>解释为元组。</p>
<p><code>a = 10,</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = (<span class="number">1</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">type</span>(a)</span><br><span class="line">&lt;<span class="keyword">class</span> <span class="string">&#x27;int&#x27;</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = (<span class="number">1</span>,)     <span class="comment"># 或者 a = 1,</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">type</span>(a)</span><br><span class="line">&lt;<span class="keyword">class</span> <span class="string">&#x27;tuple&#x27;</span>&gt;</span><br></pre></td></tr></table></figure>
<h5 id="通过tuple-创建元组"><a href="#通过tuple-创建元组" class="headerlink" title="通过tuple()创建元组"></a>通过tuple()创建元组</h5><p><code>tuple(可迭代的对象)</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="built_in">tuple</span>()  <span class="comment"># 创建一个空元组对象</span></span><br><span class="line">b = <span class="built_in">tuple</span>(<span class="string">&quot;abc&quot;</span>)</span><br><span class="line">c = <span class="built_in">tuple</span>(<span class="built_in">range</span>(<span class="number">3</span>))</span><br><span class="line">d = <span class="built_in">tuple</span>([<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>])</span><br></pre></td></tr></table></figure>
<blockquote>
<p>总结：</p>
<ol>
<li><code>tuple()</code>可以接收列表、字符串、其他序列类型、迭代器等生成元组。</li>
<li><code>list()</code>可以接收元组、字符串、其他序列类型、迭代器等生成列表。</li>
</ol>
</blockquote>
<h4 id="元组的元素访问和计数"><a href="#元组的元素访问和计数" class="headerlink" title="元组的元素访问和计数"></a>元组的元素访问和计数</h4><p>元组的元素不能修改</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = (<span class="number">20</span>,<span class="number">10</span>,<span class="number">30</span>,<span class="number">9</span>,<span class="number">8</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a[<span class="number">3</span>]=<span class="number">33</span></span><br><span class="line">Traceback (most recent call last):</span><br><span class="line">  File <span class="string">&quot;&lt;pyshell#313&gt;&quot;</span>, line <span class="number">1</span>, <span class="keyword">in</span></span><br><span class="line">&lt;module&gt;</span><br><span class="line">    a[<span class="number">3</span>]=<span class="number">33</span></span><br><span class="line">TypeError: <span class="string">&#x27;tuple&#x27;</span> <span class="built_in">object</span> does <span class="keyword">not</span> support item assignment</span><br></pre></td></tr></table></figure>
<p>元组的元素访问、index()、count()、切片等操作，和列表一样。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = (<span class="number">20</span>,<span class="number">10</span>,<span class="number">30</span>,<span class="number">9</span>,<span class="number">8</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a[<span class="number">1</span>]</span><br><span class="line"><span class="number">10</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a[<span class="number">1</span>:<span class="number">3</span>]</span><br><span class="line">(<span class="number">10</span>, <span class="number">30</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a[:<span class="number">4</span>]</span><br><span class="line">(<span class="number">20</span>, <span class="number">10</span>, <span class="number">30</span>, <span class="number">9</span>)</span><br></pre></td></tr></table></figure>
<p>列表关于排序的方法<code>list.sort()</code>是修改原列表对象，元组没有该方法。如果要对元组排序，只能使用内置函数<code>sorted(tupleObj)</code>，并生成新元组的对象。(与列表的<code>sorted(listObj)</code>一样)</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a = (<span class="number">20</span>,<span class="number">10</span>,<span class="number">30</span>,<span class="number">9</span>,<span class="number">8</span>)</span><br><span class="line">b = <span class="built_in">sorted</span>(a)    <span class="comment"># b是新对象，内容是：[8, 9, 10, 20, 30]</span></span><br></pre></td></tr></table></figure>
<h4 id="zip"><a href="#zip" class="headerlink" title="zip"></a>zip</h4><p><code>zip(列表1，列表2，...)</code>将多个列表对应位置的元素组合成为元组，并返回这个zip对象。</p>
<blockquote>
<p>:warning:如果各个迭代器的元素个数不一致，则返回列表长度==与最短的对象相同==</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>]</span><br><span class="line">b = [<span class="number">40</span>,<span class="number">50</span>,<span class="number">60</span>]</span><br><span class="line">c = [<span class="number">70</span>,<span class="number">80</span>,<span class="number">90</span>,<span class="number">100</span>]</span><br><span class="line">d = <span class="built_in">zip</span>(a,b,c)</span><br><span class="line"><span class="built_in">print</span>(d)    <span class="comment"># zip object</span></span><br><span class="line">e = <span class="built_in">list</span>(d) <span class="comment"># 列表：[(10, 40, 70), (20, 50, 80), (30, 60, 90)]</span></span><br><span class="line"><span class="built_in">print</span>(e)</span><br></pre></td></tr></table></figure>
<h4 id="生成器推导式创建元组"><a href="#生成器推导式创建元组" class="headerlink" title="生成器推导式创建元组"></a>生成器推导式创建元组</h4><ol>
<li>从形式上看，生成器推导式与列表推导式类似，只是生成器推导式使用小括号。</li>
<li>列表推导式直接生成列表对象，生成器推导式生成的不是列表也不是元组，而是一个生成器对象。</li>
<li>我们可以通过生成器对象，转化成列表或者元组。也可以使用生成器对象的 <code>__next__()</code> 方法进行遍历，或者直接作为迭代器对象来使用。不管什么方式使用，元素访问结束后，如果需要重新访问其中的元素，必须重新创建该生成器对象。</li>
</ol>
<p>【操作】生成器的使用测试</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 列表推导式： [0, 2, 4, 6, 8]</span></span><br><span class="line"><span class="comment"># a = [x*2 for x in range(5)]</span></span><br><span class="line"><span class="comment"># print(a)</span></span><br><span class="line">s = (x*<span class="number">2</span> <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">5</span>))</span><br><span class="line"><span class="built_in">print</span>(s)    <span class="comment"># &lt;generator object &lt;genexpr&gt; at 0x0000021C80BE2880&gt;</span></span><br><span class="line">b = <span class="built_in">tuple</span>(s)</span><br><span class="line"><span class="built_in">print</span>(b)    <span class="comment"># (0, 2, 4, 6, 8)</span></span><br><span class="line">c = <span class="built_in">tuple</span>(s)</span><br><span class="line"><span class="built_in">print</span>(c)    <span class="comment"># ()</span></span><br><span class="line"></span><br><span class="line">s2 = (x <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">3</span>))</span><br><span class="line"><span class="built_in">print</span>(s2.__next__())        <span class="comment">#0</span></span><br><span class="line"><span class="built_in">print</span>(s2.__next__())        <span class="comment">#1</span></span><br><span class="line"><span class="built_in">print</span>(s2.__next__())        <span class="comment">#2</span></span><br><span class="line"><span class="built_in">print</span>(s2.__next__())        <span class="comment">#报错：StopIteration</span></span><br></pre></td></tr></table></figure>
<h4 id="元组总结"><a href="#元组总结" class="headerlink" title="元组总结"></a>元组总结</h4><ol>
<li>元组的核心特点是：==不可变序列==。</li>
<li>元组的访问和处理速度比列表快。</li>
<li>与<strong>整数和字符串</strong>一样，<strong>元组可以作为字典的键</strong>，==列表则永远不能作为字典的键使用==。</li>
</ol>
<h3 id="字典"><a href="#字典" class="headerlink" title="字典"></a>字典</h3><p>字典是“键值对”的<strong>==无序可变序列==</strong>，字典中的每个元素都是一个“键值对”，包含：“键对象”和“值对象”。可以通过“键对象”实现快速获取、删除、更新对应的“值对象”。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041848499.png" alt="image-20240204184816365"></p>
<p>一个典型的字典的定义方式：</p>
<p><code>a = &#123;&#39;name&#39;:&#39;gaoqi&#39;, &#39;age&#39;:18, &#39;job&#39;:&#39;programmer&#39;&#125;</code></p>
<p>列表中我们通过“下标数字”找到对应的对象。字典中通过“键对象”找到对应的“值对象”。</p>
<blockquote>
<ol>
<li>“键”是任意的不可变数据，比如：整数、浮点数、字符串、元组。</li>
<li>但是：列表、字典、集合这些可变对象，不能作为“键”。</li>
<li>并且“键”不可重复。</li>
<li>“值”可以是任意的数据，并且可重复。</li>
</ol>
</blockquote>
<h4 id="字典的创建"><a href="#字典的创建" class="headerlink" title="字典的创建"></a>字典的创建</h4><ol>
<li><p>我们可以通过<code>&#123;&#125;</code>、<code>dict()</code>来创建字典对象。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;gaoqi&#x27;</span>,<span class="string">&#x27;age&#x27;</span>:<span class="number">18</span>,<span class="string">&#x27;job&#x27;</span>:<span class="string">&#x27;programmer&#x27;</span>&#125;</span><br><span class="line">b = <span class="built_in">dict</span>(name=<span class="string">&#x27;gaoqi&#x27;</span>,age=<span class="number">18</span>,job=<span class="string">&#x27;programmer&#x27;</span>)</span><br><span class="line">a = <span class="built_in">dict</span>([(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;gaoqi&quot;</span>),(<span class="string">&quot;age&quot;</span>,<span class="number">18</span>)])</span><br><span class="line">c = &#123;&#125;      <span class="comment"># 空的字典对象</span></span><br><span class="line">d = <span class="built_in">dict</span>()  <span class="comment"># 空的字典对象</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>通过<code>zip()</code>创建字典对象</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">k = [<span class="string">&#x27;name&#x27;</span>,<span class="string">&#x27;age&#x27;</span>,<span class="string">&#x27;job&#x27;</span>]</span><br><span class="line">v = [<span class="string">&#x27;gaoqi&#x27;</span>,<span class="number">18</span>,<span class="string">&#x27;teacher&#x27;</span>]</span><br><span class="line">d = <span class="built_in">dict</span>(<span class="built_in">zip</span>(k,v))</span><br><span class="line"><span class="built_in">print</span>(d)   <span class="comment"># &#123;&#x27;name&#x27;: &#x27;gaoqi&#x27;, &#x27;age&#x27;: 18, &#x27;job&#x27;: &#x27;techer&#x27;&#125;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>通过<code>fromkeys</code>创建值为空的字典</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">f = <span class="built_in">dict</span>.fromkeys([<span class="string">&#x27;name&#x27;</span>,<span class="string">&#x27;age&#x27;</span>,<span class="string">&#x27;job&#x27;</span>])</span><br><span class="line"><span class="built_in">print</span>(f)  <span class="comment">#结果：&#123;&#x27;name&#x27;: None, &#x27;age&#x27;: None, &#x27;job&#x27;: None&#125;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311141608677.png" alt="image-20231114145951487"></p>
<h4 id="字典元素的访问"><a href="#字典元素的访问" class="headerlink" title="字典元素的访问"></a>字典元素的访问</h4><ol>
<li><p>通过 <code>[键]</code> 获得“值”。若键不存在，则抛出异常。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;gaoqi&#x27;</span>,<span class="string">&#x27;age&#x27;</span>:<span class="number">18</span>,<span class="string">&#x27;job&#x27;</span>:<span class="string">&#x27;programmer&#x27;</span>&#125;</span><br><span class="line">b = a[<span class="string">&#x27;name&#x27;</span>]</span><br><span class="line"><span class="built_in">print</span>(b)</span><br></pre></td></tr></table></figure>
</li>
<li><p>通过<code>get()</code>方法获得“值”。❤️推荐使用。优点是：指定键不存在，返回None；也可以设定指定键不存在时默认返回的对象。推荐</p>
<p>使用<code>get()</code>获取“值对象”</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;gaoqi&#x27;</span>,<span class="string">&#x27;age&#x27;</span>:<span class="number">18</span>,<span class="string">&#x27;job&#x27;</span>:<span class="string">&#x27;programmer&#x27;</span>&#125;</span><br><span class="line">b = a.get(<span class="string">&#x27;name&#x27;</span>)</span><br><span class="line">c = a.get(<span class="string">&#x27;gender&#x27;</span>,<span class="string">&#x27;不存在&#x27;</span>)</span><br><span class="line"><span class="built_in">print</span>(b)</span><br><span class="line"><span class="built_in">print</span>(c)</span><br></pre></td></tr></table></figure>
</li>
<li><p>列出所有的键值对</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;gaoqi&#x27;</span>,<span class="string">&#x27;age&#x27;</span>:<span class="number">18</span>,<span class="string">&#x27;job&#x27;</span>:<span class="string">&#x27;programmer&#x27;</span>&#125;</span><br><span class="line">b = a.items()</span><br><span class="line"><span class="built_in">print</span>(b)      <span class="comment"># dict_items([(&#x27;name&#x27;, &#x27;gaoqi&#x27;),(&#x27;age&#x27;, 18), (&#x27;job&#x27;, &#x27;programmer&#x27;)])</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>列出所有的键，列出所有的值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;gaoqi&#x27;</span>,<span class="string">&#x27;age&#x27;</span>:<span class="number">18</span>,<span class="string">&#x27;job&#x27;</span>:<span class="string">&#x27;programmer&#x27;</span>&#125;</span><br><span class="line">k = a.keys()</span><br><span class="line">v = a.values()</span><br><span class="line"><span class="built_in">print</span>(k)  <span class="comment"># dict_keys([&#x27;name&#x27;, &#x27;age&#x27;,&#x27;job&#x27;])</span></span><br><span class="line"><span class="built_in">print</span>(v)  <span class="comment"># dict_values([&#x27;gaoqi&#x27;, 18,&#x27;programmer&#x27;])</span></span><br></pre></td></tr></table></figure>
</li>
<li><p><code>len()</code> 键值对的个数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;gaoqi&#x27;</span>,<span class="string">&#x27;age&#x27;</span>:<span class="number">18</span>,<span class="string">&#x27;job&#x27;</span>:<span class="string">&#x27;programmer&#x27;</span>&#125;</span><br><span class="line">num = <span class="built_in">len</span>(a)</span><br><span class="line"><span class="built_in">print</span>(num)   <span class="comment">#3</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>检测一个“键”是否在字典中</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;gaoqi&#x27;</span>,<span class="string">&#x27;age&#x27;</span>:<span class="number">18</span>,<span class="string">&#x27;job&#x27;</span>:<span class="string">&#x27;programmer&#x27;</span>&#125;</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;name&quot;</span> <span class="keyword">in</span> a)  <span class="comment">#True</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h4 id="字典元素的添加、修改、删除"><a href="#字典元素的添加、修改、删除" class="headerlink" title="字典元素的添加、修改、删除"></a>字典元素的添加、修改、删除</h4><ol>
<li><p>给字典新增“键值对”。如果“键”已经存在，则覆盖旧的键值对；如果“键”不存在，则新增“键值对”</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;gaoqi&#x27;</span>,<span class="string">&#x27;age&#x27;</span>:<span class="number">18</span>,<span class="string">&#x27;job&#x27;</span>:<span class="string">&#x27;programmer&#x27;</span>&#125;</span><br><span class="line">a[<span class="string">&#x27;address&#x27;</span>]=<span class="string">&#x27;西三旗1号院&#x27;</span></span><br><span class="line">a[<span class="string">&#x27;age&#x27;</span>]=<span class="number">16</span></span><br><span class="line"><span class="built_in">print</span>(a)</span><br><span class="line"><span class="comment">#&#123;&#x27;name&#x27;: &#x27;gaoqi&#x27;, &#x27;age&#x27;: 16, &#x27;job&#x27;:&#x27;programmer&#x27;, &#x27;address&#x27;: &#x27;西三旗1号院&#x27;&#125;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>使用 <code>update()</code> 将新字典中所有键值对全部添加到旧字典对象上。如果 <code>key</code> 有重复，则直接覆盖</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;gaoqi&#x27;</span>,<span class="string">&#x27;age&#x27;</span>:<span class="number">18</span>,<span class="string">&#x27;job&#x27;</span>:<span class="string">&#x27;programmer&#x27;</span>&#125;</span><br><span class="line">b = &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;gaoxixi&#x27;</span>,<span class="string">&#x27;money&#x27;</span>:<span class="number">1000</span>,<span class="string">&#x27;gender&#x27;</span>:<span class="string">&#x27;男的&#x27;</span>&#125;</span><br><span class="line">a.update(b)</span><br><span class="line"><span class="built_in">print</span>(a)</span><br><span class="line"><span class="comment"># &#123;&#x27;name&#x27;: &#x27;gaoxixi&#x27;, &#x27;age&#x27;: 18, &#x27;job&#x27;:&#x27;programmer&#x27;, &#x27;money&#x27;: 1000, &#x27;gender&#x27;: &#x27;男的&#x27;&#125;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>字典中元素的删除，可以使用 <code>del()</code> 方法；或者 <code>clear()</code> 删除所有键值对； <code>pop()</code> 删除指定键值对，并返回对应的“值对象”</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;gaoqi&#x27;</span>,<span class="string">&#x27;age&#x27;</span>:<span class="number">18</span>,<span class="string">&#x27;job&#x27;</span>:<span class="string">&#x27;programmer&#x27;</span>&#125;</span><br><span class="line"><span class="keyword">del</span>(a[<span class="string">&#x27;name&#x27;</span>])</span><br><span class="line"><span class="built_in">print</span>(a)       <span class="comment"># &#123;&#x27;age&#x27;: 18, &#x27;job&#x27;:&#x27;programmer&#x27;&#125;</span></span><br><span class="line">age = a.pop(<span class="string">&#x27;age&#x27;</span>)</span><br><span class="line"><span class="built_in">print</span>(age)     <span class="comment"># 18</span></span><br></pre></td></tr></table></figure>
</li>
<li><p><code>popitem()</code> ：随机删除和返回该键值对。<strong>字典是“无序可变序列”</strong>，因此没有第一个元素、最后一个元素的概念； <code>popitem</code> 弹出随机的项，因为字典并没有”最后的元素”或者其他有关顺序的概念。若想一个接一个地移除并处理项，这个方法就非常有效（因为不用首先获取键的列表）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;gaoqi&#x27;</span>,<span class="string">&#x27;age&#x27;</span>:<span class="number">18</span>,<span class="string">&#x27;job&#x27;</span>:<span class="string">&#x27;programmer&#x27;</span>&#125;</span><br><span class="line">r1 = a.popitem()</span><br><span class="line">r2 = a.popitem()</span><br><span class="line">r3 = a.popitem()</span><br><span class="line"><span class="built_in">print</span>(a)    <span class="comment">#&#123;&#125;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h4 id="序列解包"><a href="#序列解包" class="headerlink" title="序列解包"></a>序列解包</h4><p>序列解包可以用于<strong>元组、列表、字典</strong>。序列解包可以让我们方便的对多个变量赋值。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">x,y,z=(<span class="number">20</span>,<span class="number">30</span>,<span class="number">10</span>)</span><br><span class="line">(a,b,c)=(<span class="number">9</span>,<span class="number">8</span>,<span class="number">10</span>)</span><br><span class="line">[m,n,p]=[<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>]</span><br></pre></td></tr></table></figure>
<p>序列解包用于字典时，<strong>默认是对“键”进行操作</strong>； 如果需要对键值对操作，则需要使用<code>items()</code>；如果需要对“值”进行操作，则需要使用<code>values()</code>；</p>
<p><strong>items()对键值进行操作返回的是元组，可以通过索引获得键和值</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">s = &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;gaoqi&#x27;</span>,<span class="string">&#x27;age&#x27;</span>:<span class="number">18</span>,<span class="string">&#x27;job&#x27;</span>:<span class="string">&#x27;teacher&#x27;</span>&#125;</span><br><span class="line">name,age,job=s  <span class="comment"># 默认对键进行操作</span></span><br><span class="line"><span class="built_in">print</span>(name)     <span class="comment"># name</span></span><br><span class="line">name,age,job=s.items()  <span class="comment"># 对键值对进行操作</span></span><br><span class="line"><span class="built_in">print</span>(name)     <span class="comment"># (&#x27;name&#x27;, &#x27;gaoqi&#x27;)</span></span><br><span class="line">name,age,job=s.values() <span class="comment"># 对值进行操作</span></span><br><span class="line"><span class="built_in">print</span>(name)     <span class="comment"># gaoqi</span></span><br></pre></td></tr></table></figure>
<h4 id="表格数据使用字典和列表存储和访问"><a href="#表格数据使用字典和列表存储和访问" class="headerlink" title="表格数据使用字典和列表存储和访问"></a>表格数据使用字典和列表存储和访问</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311141608685.png" alt="image-20231114154449214"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">r1 = &#123;<span class="string">&quot;name&quot;</span>:<span class="string">&quot;高小一&quot;</span>,<span class="string">&quot;age&quot;</span>:<span class="number">18</span>,<span class="string">&quot;salary&quot;</span>:<span class="number">30000</span>,<span class="string">&quot;city&quot;</span>:<span class="string">&quot;北京&quot;</span>&#125;</span><br><span class="line">r2 = &#123;<span class="string">&quot;name&quot;</span>:<span class="string">&quot;高小二&quot;</span>,<span class="string">&quot;age&quot;</span>:<span class="number">19</span>,<span class="string">&quot;salary&quot;</span>:<span class="number">20000</span>,<span class="string">&quot;city&quot;</span>:<span class="string">&quot;上海&quot;</span>&#125;</span><br><span class="line">r3 = &#123;<span class="string">&quot;name&quot;</span>:<span class="string">&quot;高小五&quot;</span>,<span class="string">&quot;age&quot;</span>:<span class="number">20</span>,<span class="string">&quot;salary&quot;</span>:<span class="number">10000</span>,<span class="string">&quot;city&quot;</span>:<span class="string">&quot;深圳&quot;</span>&#125;</span><br><span class="line">tb = [r1,r2,r3]</span><br><span class="line"><span class="comment"># 获得第二行的人的薪资</span></span><br><span class="line"><span class="built_in">print</span>(tb[<span class="number">1</span>].get(<span class="string">&quot;salary&quot;</span>))</span><br><span class="line"><span class="comment"># 打印表中所有的的薪资</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(tb)):       <span class="comment"># i --&gt;0,1,2</span></span><br><span class="line">    <span class="built_in">print</span>(tb[i].get(<span class="string">&quot;salary&quot;</span>))</span><br><span class="line">    </span><br><span class="line"><span class="comment"># 打印表的所有数据</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(tb)):</span><br><span class="line">	<span class="built_in">print</span>(tb[i].get(<span class="string">&quot;name&quot;</span>),tb[i].get(<span class="string">&quot;age&quot;</span>),tb[i].get(<span class="string">&quot;salary&quot;</span>),tb[i].get(<span class="string">&quot;city&quot;</span>))</span><br></pre></td></tr></table></figure>
<h4 id="字典核心底层原理-重要"><a href="#字典核心底层原理-重要" class="headerlink" title="字典核心底层原理(重要)"></a>字典核心底层原理(重要)</h4><p>字典对象的核心是<strong>散列表</strong>。散列表是一个稀疏数组（总是有空白元素的数组），数组的每个单元叫做 <code>bucket</code> 。每个 <code>bucket</code> 有两部分：一个是键对象的引用，一个是值对象的引用。</p>
<p>由于，所有 <code>bucket</code> 结构和大小一致，我们可以通过偏移量来读取指定<code>bucket</code> 。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041912091.png" alt="image-20240204191242334"></p>
<h5 id="将一个键值对放进字典的底层过程"><a href="#将一个键值对放进字典的底层过程" class="headerlink" title="将一个键值对放进字典的底层过程"></a>将一个键值对放进字典的底层过程</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;&#125;</span><br><span class="line">a[<span class="string">&quot;name&quot;</span>]=<span class="string">&quot;gaoqi&quot;</span></span><br></pre></td></tr></table></figure>
<p>假设字典a对象创建完后，数组长度为8：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041913983.png" alt="image-20240204191323540"></p>
<p>我们要把<code>&quot;name&quot;=&quot;gaoqi&quot;</code>这个键值对放到字典对象a中，首先第一步需要计算键<code>&quot;name&quot;</code>的散列值。Python中可以通过<code>hash()</code>来计算。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">bin</span>(<span class="built_in">hash</span>(<span class="string">&quot;name&quot;</span>))</span><br><span class="line"><span class="string">&#x27;-0b1010111101001110110101100100101&#x27;</span></span><br></pre></td></tr></table></figure>
<p>由于数组长度为8，我们可以拿计算出的散列值的最右边3位数字作为偏移量，即<code>&quot;101&quot;</code>，十进制是数字5。我们查看偏移量5，对应的<code>bucket</code>是否为空。如果为空，则将键值对放进去。如果不为空，则依次取右边3位作为偏移量，即<code>&quot;100&quot;</code>，十进制是数字4。再查看偏移量为4的<code>bucket</code>是否为空。直到找到为空的<code>bucket</code>将键值对放进去。流程图如下：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041915971.png" alt="image-20240204191545530"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041917725.png" alt="image-20240204191702494"></p>
<p><strong>扩容</strong></p>
<ol>
<li>python会根据散列表的拥挤程度扩容。“扩容”指的是:创造更大的数组，将原有内容拷贝到新数组中。</li>
<li>接近2/3时，数组就会扩容。</li>
</ol>
<h5 id="根据键查找“键值对”的底层过程"><a href="#根据键查找“键值对”的底层过程" class="headerlink" title="根据键查找“键值对”的底层过程"></a>根据键查找“键值对”的底层过程</h5><p>明白了，一个键值对是如何存储到数组中的，根据键对象取到值对象，理解起来就简单了。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.get(<span class="string">&quot;name&quot;</span>)</span><br><span class="line"><span class="string">&#x27;gaoqi&#x27;</span></span><br></pre></td></tr></table></figure>
<p>当调用<code>a.get(&quot;name&quot;)</code>，就是根据键<code>&quot;name&quot;</code>查找到<code>&quot;键值对&quot;</code>，从而找到值对象<code>&quot;gaoqi&quot;</code>。</p>
<p>我们仍然要首先计算<code>&quot;name&quot;</code>对象的散列值：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">bin</span>(<span class="built_in">hash</span>(<span class="string">&quot;name&quot;</span>))</span><br><span class="line"><span class="string">&#x27;-0b1010111101001110110101100100101&#x27;</span></span><br></pre></td></tr></table></figure>
<p>和存储的底层流程算法一致，也是依次取散列值的不同位置的数字。 假设数组长度为8，我们可以拿计算出的散列值的最右边3位数字作为偏移量，即 <code>101</code> ，十进制是数字5。我们查看偏移量5，对应的 <code>bucket</code> 是否为空。如果为空，则返回 <code>None</code> 。如果不为空，则将这个 <code>bucket</code> 的键对象计算对应散列值，和我们的散列值进行比较，如果相等。则将对应“值对象”返回。如果不相等，则再依次取其他几位数字，重新计算偏移量。依次取完后，仍然没有找到。则返回<code>None</code> 。流程图如下：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311141608693.png" alt="image-20231114160311802"></p>
<blockquote>
<p><strong>用法总结</strong>：</p>
<ol>
<li><p>字典在内存中开销巨大，典型的空间换时间。</p>
</li>
<li><p>键查询速度很快</p>
</li>
<li><p>往字典里面添加新键值对可能导致扩容，导致散列表中键的次序变化。因此，不要在遍历字典的同时进行字典的修改</p>
</li>
<li><p>键必须可散列 </p>
<ul>
<li><p>数字、字符串、元组，都是可散列的 </p>
</li>
<li><p>自定义对象需要支持下面三点：(面向对象章节中再展开说)</p>
<p>支持 <code>hash()</code> 函数</p>
<p>支持通过 <code>__eq__()</code> 方法检测相等性</p>
<p>若 <code>a==b</code> 为真，则 <code>hash(a)==hash(b)</code> 也为真</p>
</li>
</ul>
</li>
</ol>
</blockquote>
<h3 id="集合"><a href="#集合" class="headerlink" title="集合"></a>集合</h3><p>集合是<strong>无序可变</strong>，<strong>元素不能重复</strong>。实际上，集合底层是字典实现，集合的所有元素都是字典中的“键对象”，因此是不能重复的且唯一的。</p>
<h4 id="集合创建和删除"><a href="#集合创建和删除" class="headerlink" title="集合创建和删除"></a>集合创建和删除</h4><ol>
<li><p>使用<code>&#123;&#125;</code>创建集合对象，并使用<code>add()</code>方法添加元素</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;<span class="number">3</span>,<span class="number">5</span>,<span class="number">7</span>&#125;</span><br><span class="line">a.add(<span class="number">9</span>)    <span class="comment"># &#123;9, 3, 5, 7&#125;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>使用<code>set()</code>，将列表、元组等可迭代对象转成集合。如果原来数据存在重复数据，则只保留一个</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a = [<span class="string">&#x27;a&#x27;</span>,<span class="string">&#x27;b&#x27;</span>,<span class="string">&#x27;c&#x27;</span>,<span class="string">&#x27;b&#x27;</span>]</span><br><span class="line">b = <span class="built_in">set</span>(a)    <span class="comment"># &#123;&#x27;b&#x27;, &#x27;a&#x27;, &#x27;c&#x27;&#125;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p><code>remove()</code>删除指定元素；<code>clear()</code>清空整个集合</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>,<span class="number">40</span>,<span class="number">50</span>&#125;</span><br><span class="line">a.remove(<span class="number">20</span>)   <span class="comment"># &#123;10, 50, 40,30&#125;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h4 id="集合相关操作"><a href="#集合相关操作" class="headerlink" title="集合相关操作"></a>集合相关操作</h4><p>像数学中概念一样，Python对集合也提供了并集、交集、差集等运算。我们给出示例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = &#123;<span class="number">1</span>,<span class="number">3</span>,<span class="string">&#x27;sxt&#x27;</span>&#125;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b = &#123;<span class="string">&#x27;he&#x27;</span>,<span class="string">&#x27;it&#x27;</span>,<span class="string">&#x27;sxt&#x27;</span>&#125;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a|b  <span class="comment"># 并集</span></span><br><span class="line">&#123;<span class="number">1</span>, <span class="number">3</span>, <span class="string">&#x27;sxt&#x27;</span>, <span class="string">&#x27;he&#x27;</span>, <span class="string">&#x27;it&#x27;</span>&#125;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a&amp;b  <span class="comment"># 交集</span></span><br><span class="line">&#123;<span class="string">&#x27;sxt&#x27;</span>&#125;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a-b  <span class="comment"># 差集</span></span><br><span class="line">&#123;<span class="number">1</span>, <span class="number">3</span>&#125;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.union(b)  <span class="comment"># 并集</span></span><br><span class="line">&#123;<span class="number">1</span>, <span class="number">3</span>, <span class="string">&#x27;sxt&#x27;</span>, <span class="string">&#x27;he&#x27;</span>, <span class="string">&#x27;it&#x27;</span>&#125;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.intersection(b) <span class="comment"># 交集</span></span><br><span class="line">&#123;<span class="string">&#x27;sxt&#x27;</span>&#125;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.difference(b)   <span class="comment"># 差集</span></span><br><span class="line">&#123;<span class="number">1</span>, <span class="number">3</span>&#125;</span><br></pre></td></tr></table></figure>
<h2 id="控制语句"><a href="#控制语句" class="headerlink" title="控制语句"></a>控制语句</h2><h3 id="控制语句和逻辑思维"><a href="#控制语句和逻辑思维" class="headerlink" title="控制语句和逻辑思维"></a>控制语句和逻辑思维</h3><blockquote>
<p>控制语句：把语句组合成能完成一定功能的小逻辑模块。</p>
<p>分为三类：顺序、选择和循环。</p>
<p>学会控制语句，是真正跨入编程界的“门槛”，是成为“程序猿”的“门票”。</p>
</blockquote>
<ol>
<li>“顺序结构”代表 <code>“先执行a，再执行b”</code> 的逻辑。比如，先找个女朋友，再给女朋友打电话；先订婚，再结婚；</li>
<li>“条件判断结构”代表 <code>“如果…，则…”</code> 的逻辑。比如，如果女朋友来电，则迅速接电话；如果看到红灯，则停车；</li>
<li>“循环结构”代表 <code>“如果…，则重复执行…”</code> 的逻辑。比如，如果没打通女朋友电话，则再继续打一次； 如果没找到喜欢的人，则再继续找</li>
</ol>
<p>很神奇的是，三种流程控制语句就能表示所有的事情！</p>
<h3 id="选择结构-条件判断结构"><a href="#选择结构-条件判断结构" class="headerlink" title="选择结构(条件判断结构)"></a>选择结构(条件判断结构)</h3><p>选择结构通过判断条件是否成立，来决定执行哪个分支。选择结构有多种形式，分为：单分支、双分支、多分支。</p>
<h4 id="单分支选择结构"><a href="#单分支选择结构" class="headerlink" title="单分支选择结构"></a>单分支选择结构</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041932603.png" alt="image-20240204193246251"></p>
<p>if语句单分支结构的语法形式如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> 条件表达式:</span><br><span class="line">	语句/语句块</span><br></pre></td></tr></table></figure>
<blockquote>
<ol>
<li>条件表达式：可以是逻辑表达式、关系表达式、算术表达式等等。</li>
<li>语句/语句块：可以是一条语句，也可以是多条语句。多条语句，缩进必须对齐一致</li>
</ol>
</blockquote>
<h4 id="条件表达式详解"><a href="#条件表达式详解" class="headerlink" title="条件表达式详解"></a>条件表达式详解</h4><p>在选择和循环结构中，条件表达式的值为 <code>False</code> 的情况如下：</p>
<p>False、0、0.0、空值None、空序列对象（空列表、空元祖、空集合、空字典、空字符串）、空range对象、空迭代对象。</p>
<p><strong>其他情况，均为</strong> <strong><code>True</code></strong> 。这么看来，Python所有的合法表达式都可以看做条件表达式，甚至包括函数调用的表达式。</p>
<p>【操作】测试各种条件表达式</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> <span class="number">3</span>:    <span class="comment"># 整数作为条件表达式</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;ok&quot;</span>)</span><br><span class="line">a = []   <span class="comment"># 列表作为条件表达式，由于为空列表，是False</span></span><br><span class="line"><span class="keyword">if</span> a:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;空列表，False&quot;</span>)</span><br><span class="line">s = <span class="string">&quot;False&quot;</span>    <span class="comment"># 非空字符串，是True</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> s:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;非空字符串，是True&quot;</span>)</span><br><span class="line">    </span><br><span class="line">c = <span class="number">9</span></span><br><span class="line"><span class="keyword">if</span> <span class="number">3</span>&lt;c&lt;<span class="number">20</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;3&lt;c&lt;20&quot;</span>)</span><br><span class="line">    </span><br><span class="line"><span class="keyword">if</span> <span class="number">3</span>&lt;c  <span class="keyword">and</span>  c&lt;<span class="number">20</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;3&lt;c and c&lt;20&quot;</span>)</span><br><span class="line">    </span><br><span class="line"><span class="keyword">if</span> <span class="literal">True</span>:        <span class="comment"># 布尔值</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;True&quot;</span>)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>:warning:条件表达式中，不能有赋值操作符 <code>=</code></p>
<p>在Python中，条件表达式不能出现赋值操作符 <code>=</code> ，避免了其他语言中经常误将关系运算符 <code>==</code> 写作赋值运算符 <code>=</code> 带来的困扰。</p>
<p>如下代码将会报语法错误：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> <span class="number">3</span> &lt; c <span class="keyword">and</span> (c=<span class="number">20</span>):   <span class="comment"># 直接报语法错误！</span></span><br><span class="line">	<span class="built_in">print</span>(<span class="string">&quot;赋值符不能出现在条件表达式中&quot;</span>)</span><br></pre></td></tr></table></figure>
</blockquote>
<h4 id="双分支选择结构"><a href="#双分支选择结构" class="headerlink" title="双分支选择结构"></a>双分支选择结构</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041944091.png" alt="image-20240204194426609"></p>
<p>双分支结构的语法格式如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> 条件表达式:</span><br><span class="line">    语句<span class="number">1</span>/语句块<span class="number">1</span></span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    语句<span class="number">2</span>/语句块<span class="number">2</span></span><br></pre></td></tr></table></figure>
<p>【操作】输入一个数字，小于10，则打印该数字；大于10，则打印“数字太大”</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">num = <span class="built_in">input</span>(<span class="string">&quot;输入一个数字：&quot;</span>)</span><br><span class="line"><span class="keyword">if</span> <span class="built_in">int</span>(num)&lt;<span class="number">10</span>:</span><br><span class="line">    <span class="built_in">print</span>(num)</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;数字太大&quot;</span>)</span><br></pre></td></tr></table></figure>
<h4 id="三元条件运算符"><a href="#三元条件运算符" class="headerlink" title="三元条件运算符"></a>三元条件运算符</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402041945029.png" alt="image-20240204194548177"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">条件为真时的值 <span class="keyword">if</span> (条件表达式) <span class="keyword">else</span> 条件为假时的值</span><br></pre></td></tr></table></figure>
<p>上一个案例代码，可以用三元条件运算符实现：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">num = <span class="built_in">input</span>(<span class="string">&quot;输入一个数字:&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(num + <span class="string">&quot;&lt;10&quot;</span> <span class="keyword">if</span>(<span class="built_in">int</span>(num) &lt; <span class="number">10</span>) <span class="keyword">else</span> <span class="built_in">str</span>(num) + <span class="string">&quot;&gt;10&quot;</span>)</span><br></pre></td></tr></table></figure>
<p>可以看到，这种写法更加简洁，易读。</p>
<h4 id="多分支选择结构"><a href="#多分支选择结构" class="headerlink" title="多分支选择结构"></a>多分支选择结构</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311161759581.png" alt="image-20231114164837210"></p>
<p>多分支选择结构的语法格式如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> 条件表达式<span class="number">1</span> :</span><br><span class="line">    语句<span class="number">1</span>/语句块<span class="number">1</span></span><br><span class="line"><span class="keyword">elif</span> 条件表达式<span class="number">2</span>:</span><br><span class="line"> 	语句<span class="number">2</span>/语句块<span class="number">2</span></span><br><span class="line">...</span><br><span class="line"><span class="keyword">elif</span> 条件表达式n :</span><br><span class="line"> 	语句n/语句块n</span><br><span class="line">[<span class="keyword">else</span>:</span><br><span class="line"> 	语句n+<span class="number">1</span>/语句块n+<span class="number">1</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<blockquote>
<p>:warning:多分支结构，几个分支之间是有逻辑关系的，不能随意颠倒顺序</p>
</blockquote>
<p>【操作】输入一个学生的成绩，将其转化成简单描述：不及格(小于60)、及格(60-79)、良好(80-89)、优秀(90-100)</p>
<p>方法1（使用完整的条件表达）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">score = <span class="built_in">int</span>(<span class="built_in">input</span>(<span class="string">&quot;请输入分数&quot;</span>))</span><br><span class="line">grade = <span class="string">&#x27;&#x27;</span></span><br><span class="line"><span class="keyword">if</span>(score&lt;<span class="number">60</span>):</span><br><span class="line">  	grade = <span class="string">&quot;不及格&quot;</span></span><br><span class="line"><span class="keyword">if</span>(<span class="number">60</span>&lt;=score&lt;<span class="number">80</span>):</span><br><span class="line">  	 grade = <span class="string">&quot;及格&quot;</span></span><br><span class="line"><span class="keyword">if</span>(<span class="number">80</span>&lt;=score&lt;<span class="number">90</span>):</span><br><span class="line">    grade = <span class="string">&quot;良好&quot;</span></span><br><span class="line"><span class="keyword">if</span>(<span class="number">90</span>&lt;=score&lt;=<span class="number">100</span>):</span><br><span class="line">  	 grade = <span class="string">&quot;优秀&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;分数是&#123;0&#125;,等级是&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(score,grade))</span><br></pre></td></tr></table></figure>
<blockquote>
<p>上面的每个分支都使用了独立的、完整的判断，顺序可以随意挪动，而不影响程序运行。</p>
</blockquote>
<p>方法2（利用多分支结构）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="string">### 多分支选择结构</span></span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line">score = <span class="built_in">input</span>(<span class="string">&quot;输入学生分数：&quot;</span>)</span><br><span class="line">grade = <span class="string">&#x27;&#x27;</span></span><br><span class="line"><span class="keyword">if</span> <span class="number">0</span> &lt;= <span class="built_in">int</span>(score) &lt; <span class="number">60</span>:</span><br><span class="line">    grade = <span class="string">&quot;不及格&quot;</span></span><br><span class="line"><span class="keyword">elif</span> <span class="built_in">int</span>(score) &lt; <span class="number">80</span>:  <span class="comment"># 60&lt;=score&lt;=80  多分支之间具有逻辑关系</span></span><br><span class="line">    grade = <span class="string">&quot;及格&quot;</span></span><br><span class="line"><span class="keyword">elif</span> <span class="built_in">int</span>(score) &lt; <span class="number">90</span>:</span><br><span class="line">    grade = <span class="string">&quot;良好&quot;</span></span><br><span class="line"><span class="keyword">elif</span> <span class="built_in">int</span>(score) &lt;= <span class="number">100</span>:</span><br><span class="line">    grade = <span class="string">&quot;优秀&quot;</span></span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    grade = <span class="string">&quot;成绩输入错误&quot;</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;分数是&#123;0&#125;，等级是&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(score, grade))</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<blockquote>
<p>:warning:多分支结构，几个分支之间是有逻辑关系的，不能随意颠倒顺序</p>
</blockquote>
<h4 id="选择结构的嵌套"><a href="#选择结构的嵌套" class="headerlink" title="选择结构的嵌套"></a>选择结构的嵌套</h4><p>选择结构可以嵌套，使用时一定要注意控制好不同级别代码块的缩进量，因为缩进量决定了代码的从属关系。</p>
<p>【操作】输入一个分数。分数在0-100之间。90以上是A,80以上是B，70以上是C，60以上是D。60以下是E</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">score = <span class="built_in">int</span>(<span class="built_in">input</span>(<span class="string">&quot;输入一个0-100之间的数字：&quot;</span>))</span><br><span class="line">grade = <span class="string">&#x27;&#x27;</span></span><br><span class="line"><span class="keyword">if</span> score &gt; <span class="number">100</span> <span class="keyword">or</span> score &lt; <span class="number">0</span>:</span><br><span class="line">    score = <span class="built_in">int</span>(<span class="built_in">input</span>(<span class="string">&quot;输入错误，请重新输入0-100之间的数字：&quot;</span>))</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="keyword">if</span> score &gt;= <span class="number">90</span>:</span><br><span class="line">        grade = <span class="string">&#x27;A&#x27;</span></span><br><span class="line">    <span class="keyword">elif</span> score &gt;= <span class="number">80</span>:</span><br><span class="line">        grade = <span class="string">&#x27;B&#x27;</span></span><br><span class="line">    <span class="keyword">elif</span> score &gt;= <span class="number">70</span>:</span><br><span class="line">        grade = <span class="string">&#x27;C&#x27;</span></span><br><span class="line">    <span class="keyword">elif</span> score &gt;= <span class="number">60</span>:</span><br><span class="line">        grade = <span class="string">&#x27;D&#x27;</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        grade = <span class="string">&#x27;E&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;分数是&#123;0&#125;，等级是&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(score, grade))</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 更少的代码方法</span></span><br><span class="line">score = <span class="built_in">int</span>(<span class="built_in">input</span>(<span class="string">&quot;输入一个0-100之间的数字：&quot;</span>))</span><br><span class="line">grade = <span class="string">&#x27;ABCDE&#x27;</span></span><br><span class="line"><span class="keyword">if</span> score &gt; <span class="number">100</span> <span class="keyword">or</span> score &lt; <span class="number">0</span>:</span><br><span class="line">    score = <span class="built_in">int</span>(<span class="built_in">input</span>(<span class="string">&quot;输入错误，请重新输入0-100之间的数字：&quot;</span>))</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    num = score // <span class="number">10</span></span><br><span class="line">    <span class="keyword">if</span> num &lt; <span class="number">6</span>:</span><br><span class="line">        num = <span class="number">5</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;分数是&#123;0&#125;，等级是&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(score, grade[<span class="number">9</span>-num]))</span><br></pre></td></tr></table></figure>
<h3 id="循环结构"><a href="#循环结构" class="headerlink" title="循环结构"></a>循环结构</h3><p>循环结构用来重复执行一条或多条语句。表达这样的逻辑：如果符合条件，则反复执行循环体里的语句。在每次执行完后都会判断一次条件是否为<code>True</code>，如果为<code>True</code>则重复执行循环体里的语句。图示如下：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202405192302240.png" alt="image-20240204195836334"></p>
<p>循环体里面的语句至少应该包含改变条件表达式的语句，以使循环趋于结束；否则，就会变成一个死循环。</p>
<h4 id="while循环"><a href="#while循环" class="headerlink" title="while循环"></a>while循环</h4><p>while循环的语法格式如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> 条件表达式：</span><br><span class="line">	循环体语句</span><br></pre></td></tr></table></figure>
<p>【操作】利用while循环，计算1-100之间数字的累加和；计算1-100之间偶数的累加和，计算1-100之间奇数的累加和</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">num = <span class="number">0</span></span><br><span class="line">sum_all = <span class="number">0</span>          <span class="comment"># 1-100所有数的累加和</span></span><br><span class="line"><span class="keyword">while</span> num&lt;=<span class="number">100</span>:</span><br><span class="line">  	sum_all += num</span><br><span class="line">   	num += <span class="number">1</span>         <span class="comment"># 迭代，改变条件表达式，使循环趋于结束</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;1-100所有数的累加和&quot;</span>,sum_all)</span><br></pre></td></tr></table></figure>
<h4 id="for循环和可迭代对象遍历"><a href="#for循环和可迭代对象遍历" class="headerlink" title="for循环和可迭代对象遍历"></a>for循环和可迭代对象遍历</h4><p>for循环通常用于可迭代对象的遍历。for循环的语法格式如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>  变量   <span class="keyword">in</span>  可迭代对象：</span><br><span class="line"> 	循环体语句</span><br></pre></td></tr></table></figure>
<p>【操作】遍历一个元组或列表</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> (<span class="number">20</span>, <span class="number">30</span>, <span class="number">50</span>):</span><br><span class="line">    <span class="built_in">print</span>(x*<span class="number">3</span>)</span><br></pre></td></tr></table></figure>
<h4 id="可迭代对象"><a href="#可迭代对象" class="headerlink" title="可迭代对象"></a>可迭代对象</h4><p>Python包含以下几种可迭代对象：</p>
<ol>
<li>序列。包含：字符串、列表、元组、字典、集合</li>
<li>迭代器对象（iterator）</li>
<li>生成器函数（generator）</li>
<li>文件对象</li>
</ol>
<p>我们已经在前面学习了序列、字典等知识，迭代器对象和生成器函数将在后面进行详解。接下来，我们通过循环来遍历这几种类型的数据：</p>
<p>【操作】遍历字符串中的字符</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> temp <span class="keyword">in</span> <span class="string">&quot;weqwewe&quot;</span>:</span><br><span class="line">    <span class="built_in">print</span>(x)</span><br></pre></td></tr></table></figure>
<p>【操作】遍历字典</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">d = &#123;<span class="string">&quot;name&quot;</span>: <span class="string">&quot;haha&quot;</span>, <span class="string">&quot;age&quot;</span>: <span class="number">12</span>, <span class="string">&quot;sex&quot;</span>: <span class="string">&quot;male&quot;</span>&#125;</span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> d:           <span class="comment"># 遍历字典所以key</span></span><br><span class="line">    <span class="built_in">print</span>(x)</span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> d.keys():    <span class="comment"># 遍历字典所有的key</span></span><br><span class="line">    <span class="built_in">print</span>(x)</span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> d.values():  <span class="comment"># 遍历字典所有的value</span></span><br><span class="line">    <span class="built_in">print</span>(x)</span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> d.items():   <span class="comment"># 遍历字典所有键值对</span></span><br><span class="line">    <span class="built_in">print</span>(x)</span><br></pre></td></tr></table></figure>
<h4 id="range对象"><a href="#range对象" class="headerlink" title="range对象"></a>range对象</h4><p><code>range对象</code>是一个迭代器对象，用来产生指定范围的数字序列。格式为：</p>
<p><code>range(start, end [,step])</code></p>
<p>生成的数值序列从 <code>start</code> 开始到 <code>end</code> 结束（⚠️<strong>不包含 end ,包头不包尾</strong>）。若没有填写 <code>start</code> ，则默认从0开始。 <code>step</code> 是可选的步长，默认为1。如下是几种典型示例：</p>
<p><code>for i in range(10)</code>          产生序列：0 1 2 3 4 5 6 7 8 9</p>
<p><code>for i in range(3,10)</code>      产生序列：3 4 5 6 7 8 9 </p>
<p><code>for i in range(3,10,2)</code>  产生序列：3 5 7 9 </p>
<p>【操作】利用for循环，计算1-100之间数字的累加和；计算1-100之间偶数的累加和，计算1-100之间奇数的累加和。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">3</span>, <span class="number">10</span>, <span class="number">2</span>):  <span class="comment"># start=3 end=10 step=2 包头不包尾</span></span><br><span class="line">    <span class="built_in">print</span>(x, end=<span class="string">&#x27;\t&#x27;</span>)</span><br><span class="line">    </span><br><span class="line"><span class="comment"># 计算1-100累加和，奇数累加和，偶数累加和</span></span><br><span class="line">sum_all = <span class="number">0</span></span><br><span class="line">sum_even = <span class="number">0</span></span><br><span class="line">sum_odd = <span class="number">0</span></span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">101</span>):</span><br><span class="line">    sum_all += x</span><br><span class="line">    <span class="keyword">if</span> x % <span class="number">2</span> == <span class="number">0</span>:</span><br><span class="line">        sum_even += x</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        sum_odd += x</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;1-100累加和&#123;0&#125;，奇数累加和&#123;1&#125;，偶数累加和&#123;2&#125;&quot;</span>.<span class="built_in">format</span>(sum_all, sum_odd, sum_even))</span><br></pre></td></tr></table></figure>
<h4 id="嵌套循环"><a href="#嵌套循环" class="headerlink" title="嵌套循环"></a>嵌套循环</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311161759588.png" alt="image-20231116160125551"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311161759589.png" alt="image-20231116160157632"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">5</span>):</span><br><span class="line">    <span class="keyword">for</span> y <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">5</span>):</span><br><span class="line">        <span class="built_in">print</span>(x, end=<span class="string">&quot;\t&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>()</span><br></pre></td></tr></table></figure>
<h5 id="嵌套循环练习"><a href="#嵌套循环练习" class="headerlink" title="嵌套循环练习"></a>嵌套循环练习</h5><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311161759590.png" alt="image-20231116160523325"></p>
<p>【操作】利用嵌套循环打印九九乘法表</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 九九乘法表</span></span><br><span class="line"><span class="keyword">for</span> m <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, <span class="number">10</span>):</span><br><span class="line">    <span class="keyword">for</span> n <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, m+<span class="number">1</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;&#123;0&#125;*&#123;1&#125;=&#123;2&#125;&quot;</span>.<span class="built_in">format</span>(m, n, m*n), end=<span class="string">&quot;\t&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>()</span><br><span class="line"></span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="string">1*1=1	</span></span><br><span class="line"><span class="string">2*1=2	2*2=4	</span></span><br><span class="line"><span class="string">3*1=3	3*2=6	3*3=9	</span></span><br><span class="line"><span class="string">4*1=4	4*2=8	4*3=12	4*4=16	</span></span><br><span class="line"><span class="string">5*1=5	5*2=10	5*3=15	5*4=20	5*5=25	</span></span><br><span class="line"><span class="string">6*1=6	6*2=12	6*3=18	6*4=24	6*5=30	6*6=36	</span></span><br><span class="line"><span class="string">7*1=7	7*2=14	7*3=21	7*4=28	7*5=35	7*6=42	7*7=49	</span></span><br><span class="line"><span class="string">8*1=8	8*2=16	8*3=24	8*4=32	8*5=40	8*6=48	8*7=56	8*8=64	</span></span><br><span class="line"><span class="string">9*1=9	9*2=18	9*3=27	9*4=36	9*5=45	9*6=54	9*7=63	9*8=72	9*9=81	</span></span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span></span><br></pre></td></tr></table></figure>
<p>【操作】用列表和字典存储下表信息，并打印出表中工资高于15000的数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 用列表和字典存储下表信息，并打印出表中工资高于15000的数据</span></span><br><span class="line">r1 = <span class="built_in">dict</span>(name=<span class="string">&quot;hycs&quot;</span>, age=<span class="number">18</span>, salary=<span class="number">10000</span>, city=<span class="string">&quot;shanghai&quot;</span>)</span><br><span class="line">r2 = <span class="built_in">dict</span>(name=<span class="string">&quot;sdaw&quot;</span>, age=<span class="number">28</span>, salary=<span class="number">20000</span>, city=<span class="string">&quot;beijing&quot;</span>)</span><br><span class="line">r3 = <span class="built_in">dict</span>(name=<span class="string">&quot;e1qe&quot;</span>, age=<span class="number">38</span>, salary=<span class="number">30000</span>, city=<span class="string">&quot;nanjing&quot;</span>)</span><br><span class="line">tb = [r1, r2, r3]</span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> tb:</span><br><span class="line">    <span class="keyword">if</span> x.get(<span class="string">&quot;salary&quot;</span>)&gt;<span class="number">15000</span>:</span><br><span class="line">        <span class="built_in">print</span>(x)</span><br></pre></td></tr></table></figure>
<h4 id="break语句"><a href="#break语句" class="headerlink" title="break语句"></a>break语句</h4><p>break语句可用于while和for循环，用来结束整个循环。当有嵌套循环时，break语句只能跳出最近一层的循环。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402042008699.png" alt="image-20240204200808384"></p>
<p>【操作】使用break语句结束循环</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">  	a = <span class="built_in">input</span>(<span class="string">&quot;请输入一个字符（输入Q或q结束）&quot;</span>)</span><br><span class="line">  	<span class="keyword">if</span> a.upper()==<span class="string">&#x27;Q&#x27;</span>:</span><br><span class="line">       	<span class="built_in">print</span>(<span class="string">&quot;循环结束，退出&quot;</span>)</span><br><span class="line">       	<span class="keyword">break</span>    </span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">       	<span class="built_in">print</span>(a)</span><br></pre></td></tr></table></figure>
<h4 id="continue语句"><a href="#continue语句" class="headerlink" title="continue语句"></a>continue语句</h4><p>continue语句用于结束本次循环，继续下一次。多个循环嵌套时，continue也是应用于最近的一层循环。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402042009191.png" alt="image-20240204200942740"></p>
<p>【操作】要求输入员工的薪资，若薪资小于0则重新输入。最后打印出录入员工的数量和薪资明细，以及平均薪资</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 要求输入员工的薪资，若薪资小于0则重新输入。最后打印出录入员王的数量和薪资明细，以及平均薪资</span></span><br><span class="line">empNum = <span class="number">0</span></span><br><span class="line">salarySum = <span class="number">0</span></span><br><span class="line">salarys = []</span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    s = <span class="built_in">input</span>(<span class="string">&quot;请输入员工薪资（按Q或q退出）&quot;</span>)</span><br><span class="line">    <span class="keyword">if</span> s.upper() == <span class="string">&quot;Q&quot;</span>:</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">if</span> <span class="built_in">float</span>(s) &lt; <span class="number">0</span>:</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;无效录入，请重新录入&quot;</span>)</span><br><span class="line">        <span class="keyword">continue</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;录入成功&quot;</span>)</span><br><span class="line">    empNum += <span class="number">1</span></span><br><span class="line">    salarySum += <span class="built_in">float</span>(s)</span><br><span class="line">    salarys.append(<span class="built_in">float</span>(s))</span><br><span class="line">    </span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;员工数&quot;</span>, <span class="built_in">format</span>(empNum))</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;录入薪资：&quot;</span>, salarys)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;总薪资：&quot;</span>, salarySum)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;平均薪资&quot;</span>, salarySum / empNum)</span><br></pre></td></tr></table></figure>
<h4 id="else语句"><a href="#else语句" class="headerlink" title="else语句"></a>else语句</h4><p><code>while</code>、<code>for</code>循环可以附带一个<code>else</code>语句（可选）。如果<code>for</code>、<code>while</code>语句没有被<code>break</code>语句结束，则会执行<code>else</code>子句，否则不执行。语法格式如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span>  条件表达式：</span><br><span class="line">	循环体</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">	语句块</span><br><span class="line"></span><br><span class="line">或者：</span><br><span class="line"><span class="keyword">for</span>  变量  <span class="keyword">in</span>  可迭代对象：</span><br><span class="line">	循环体</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">	语句块</span><br></pre></td></tr></table></figure>
<p>【操作】员工一共4人。录入这4位员工的薪资。全部录入后，打印提示“您已经全部录入4名员工的薪资”。最后，打印输出录入的薪资和平均薪资</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">salarySum = <span class="number">0</span></span><br><span class="line">salarys = []</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">4</span>):</span><br><span class="line">    s = <span class="built_in">input</span>(<span class="string">&quot;请输入员工薪资（按Q或q退出）&quot;</span>)</span><br><span class="line">    <span class="keyword">if</span> s.upper() == <span class="string">&quot;Q&quot;</span>:</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">if</span> <span class="built_in">float</span>(s) &lt; <span class="number">0</span>:</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;无效录入，请重新录入&quot;</span>)</span><br><span class="line">        <span class="keyword">continue</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;录入成功&quot;</span>)</span><br><span class="line">    salarySum += <span class="built_in">float</span>(s)</span><br><span class="line">    salarys.append(<span class="built_in">float</span>(s))</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;全部录入成功&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;录入薪资：&quot;</span>, salarys)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;总薪资：&quot;</span>, salarySum)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;平均薪资&quot;</span>, salarySum / <span class="number">4</span>)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">请输入员工薪资（按Q或q退出）40</span></span><br><span class="line"><span class="string">录入成功</span></span><br><span class="line"><span class="string">请输入员工薪资（按Q或q退出）50</span></span><br><span class="line"><span class="string">录入成功</span></span><br><span class="line"><span class="string">请输入员工薪资（按Q或q退出）60</span></span><br><span class="line"><span class="string">录入成功</span></span><br><span class="line"><span class="string">请输入员工薪资（按Q或q退出）70</span></span><br><span class="line"><span class="string">录入成功</span></span><br><span class="line"><span class="string">全部录入成功</span></span><br><span class="line"><span class="string">录入薪资： [40.0, 50.0, 60.0, 70.0]</span></span><br><span class="line"><span class="string">总薪资： 220.0</span></span><br><span class="line"><span class="string">平均薪资 55.0</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311161759594.png" alt="image-20231116164105716"></p>
<h4 id="循环代码优化技巧"><a href="#循环代码优化技巧" class="headerlink" title="循环代码优化技巧"></a>循环代码优化技巧</h4><p>虽然计算机越来越快，空间也越来越大，我们仍然要在性能问题上“斤斤计较”。编写循环时，遵守下面三个原则可以大大提高运行效率，避免不必要的低效计算：</p>
<ol>
<li>尽量减少循环内部不必要的计算</li>
<li>嵌套循环中，尽量减少内层循环的计算，尽可能向外提</li>
<li>局部变量查询较快，尽量使用局部变量</li>
</ol>
<p><strong>其他优化手段</strong></p>
<ol>
<li>==连接多个字符串或列表，使用join()或append()而不使用+==     +会创建新的字符串，join不会</li>
<li>==列表进行元素插入和删除，尽量在列表尾部操作==</li>
</ol>
<h4 id="zip-并行送代多个序列"><a href="#zip-并行送代多个序列" class="headerlink" title="zip()并行送代多个序列"></a>zip()并行送代多个序列</h4><p>我们可以通过zip()函数对多个序列进行并行迭代，zip()函数在最短序列“用完”时就会停止。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311161759597.png" alt="image-20231116165017217"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">names = (<span class="string">&quot;haohao&quot;</span>, <span class="string">&quot;hehe&quot;</span>, <span class="string">&quot;huaiyue&quot;</span>)</span><br><span class="line">ages = (<span class="number">18</span>, <span class="number">19</span>, <span class="number">20</span>)</span><br><span class="line">jobs = (<span class="string">&quot;IT&quot;</span>, <span class="string">&quot;TEACHER&quot;</span>, <span class="string">&quot;POLICE&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 使用zip并行迭代多个序列</span></span><br><span class="line"><span class="keyword">for</span> name, age, job <span class="keyword">in</span> <span class="built_in">zip</span>(names, ages, jobs):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;&#123;0&#125;--&#123;1&#125;--&#123;2&#125;&quot;</span>.<span class="built_in">format</span>(name, age, job))</span><br><span class="line">    </span><br><span class="line"><span class="comment"># 不使用zip也可以并使迭代多个序列</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">min</span>(<span class="built_in">len</span>(names), <span class="built_in">len</span>(ages), <span class="built_in">len</span>(jobs))):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;&#123;0&#125;--&#123;1&#125;--&#123;2&#125;&quot;</span>.<span class="built_in">format</span>(names[i], ages[i], jobs[i]))</span><br></pre></td></tr></table></figure>
<h3 id="推导式创建序列"><a href="#推导式创建序列" class="headerlink" title="推导式创建序列"></a>推导式创建序列</h3><p>推导式是从一个或者多个迭代器快速创建序列的一种方法。它可以将循环和条件判断结合，从而避免冗长的代码。</p>
<blockquote>
<p>❤️推导式是典型的Python风格，会使用它，代表你已经超过Python初学者的水平。</p>
</blockquote>
<h4 id="列表推导式"><a href="#列表推导式" class="headerlink" title="列表推导式"></a>列表推导式</h4><p>列表推导式生成列表对象，语法如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[表达式  <span class="keyword">for</span>  item  <span class="keyword">in</span> 可迭代对象 ]</span><br><span class="line">或者：</span><br><span class="line">&#123;表达式  <span class="keyword">for</span>  item  <span class="keyword">in</span> 可迭代对象  <span class="keyword">if</span>  条件判断&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">[x <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>,<span class="number">5</span>)] 	<span class="comment">#[1, 2, 3, 4]</span></span><br><span class="line">[x*<span class="number">2</span> <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>,<span class="number">5</span>)] 	<span class="comment">#[2, 4, 6, 8]</span></span><br><span class="line">[x*<span class="number">2</span> <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>,<span class="number">20</span>) <span class="keyword">if</span> x%<span class="number">5</span>==<span class="number">0</span> ] <span class="comment">#[10,20, 30]</span></span><br><span class="line">[a  <span class="keyword">for</span>  a  <span class="keyword">in</span> <span class="string">&quot;abcdefg&quot;</span>] 	<span class="comment">#[&#x27;a&#x27;, &#x27;b&#x27;, &#x27;c&#x27;,&#x27;d&#x27;, &#x27;e&#x27;, &#x27;f&#x27;, &#x27;g&#x27;]</span></span><br><span class="line"><span class="comment"># 可以使用两个循环,使用zip并行迭代</span></span><br><span class="line">cells = [(row,col) <span class="keyword">for</span>  row,col <span class="keyword">in</span> <span class="built_in">zip</span>(<span class="built_in">range</span>(<span class="number">1</span>,<span class="number">10</span>),<span class="built_in">range</span>(<span class="number">101</span>,<span class="number">110</span>))]</span><br><span class="line"><span class="built_in">print</span>(cells)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">a = [x <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, <span class="number">10</span>) <span class="keyword">if</span> x % <span class="number">2</span> == <span class="number">0</span>]</span><br><span class="line"><span class="built_in">print</span>(a)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">cells = [(row, column) <span class="keyword">for</span> row, column <span class="keyword">in</span> <span class="built_in">zip</span>(<span class="built_in">range</span>(<span class="number">1</span>, <span class="number">10</span>), <span class="built_in">range</span>(<span class="number">101</span>, <span class="number">110</span>))]</span><br><span class="line"><span class="built_in">print</span>(cells)</span><br><span class="line">    </span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="string">[2, 4, 6, 8]</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">[(1, 101), (2, 102), (3, 103), (4, 104), (5, 105), (6, 106), (7, 107), (8, 108), (9, 109)]</span></span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span></span><br></pre></td></tr></table></figure>
<h4 id="字典推导式"><a href="#字典推导式" class="headerlink" title="字典推导式"></a>字典推导式</h4><p>字典的推导式生成字典对象，格式如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;key_expression: value_expression  <span class="keyword">for</span>  表达式 <span class="keyword">in</span>  可迭代对象&#125;</span><br></pre></td></tr></table></figure>
<p>类似于列表推导式，字典推导也可以增加if条件判断、多个for循环。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">values = [<span class="string">&quot;北京&quot;</span>,<span class="string">&quot;上海&quot;</span>,<span class="string">&quot;深圳&quot;</span>,<span class="string">&quot;广州&quot;</span>]</span><br><span class="line">cities = &#123;<span class="built_in">id</span>*<span class="number">100</span>:city <span class="keyword">for</span> <span class="built_in">id</span>,city <span class="keyword">in</span> <span class="built_in">zip</span>(<span class="built_in">range</span>(<span class="number">1</span>,<span class="number">5</span>),values)&#125;</span><br><span class="line"><span class="built_in">print</span>(cities)</span><br></pre></td></tr></table></figure>
<p>生成字典对象：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;<span class="number">100</span>: <span class="string">&#x27;北京&#x27;</span>, <span class="number">200</span>: <span class="string">&#x27;上海&#x27;</span>, <span class="number">300</span>: <span class="string">&#x27;深圳&#x27;</span>, <span class="number">400</span>:<span class="string">&#x27;广州&#x27;</span>&#125;</span><br></pre></td></tr></table></figure>
<p>【操作】统计文本中字符出现的次数：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 统计字数</span></span><br><span class="line">my_text = <span class="string">&#x27;i love python, me too&#x27;</span></span><br><span class="line">char_count = &#123;c: my_text.count(c) <span class="keyword">for</span> c <span class="keyword">in</span> my_text&#125;</span><br><span class="line"><span class="built_in">print</span>(char_count)</span><br><span class="line"></span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="string">&#123;&#x27;i&#x27;: 1, &#x27; &#x27;: 4, &#x27;l&#x27;: 1, &#x27;o&#x27;: 4, &#x27;v&#x27;: 1, &#x27;e&#x27;: 2, &#x27;p&#x27;: 1, &#x27;y&#x27;: 1, &#x27;t&#x27;: 2, &#x27;h&#x27;: 1, &#x27;n&#x27;: 1, &#x27;,&#x27;: 1, &#x27;m&#x27;: 1&#125;</span></span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span></span><br></pre></td></tr></table></figure>
<h4 id="集合推导式"><a href="#集合推导式" class="headerlink" title="集合推导式"></a>集合推导式</h4><p>集合推导式生成集合，和列表推导式的语法格式类似：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;表达式  <span class="keyword">for</span>  item  <span class="keyword">in</span> 可迭代对象 &#125;</span><br><span class="line">或者：</span><br><span class="line">&#123;表达式  <span class="keyword">for</span>  item  <span class="keyword">in</span> 可迭代对象  <span class="keyword">if</span>  条件判断&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>&#123;x <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>,<span class="number">100</span>) <span class="keyword">if</span> x%<span class="number">9</span>==<span class="number">0</span>&#125;</span><br><span class="line">&#123;<span class="number">99</span>, <span class="number">36</span>, <span class="number">72</span>, <span class="number">9</span>, <span class="number">45</span>, <span class="number">81</span>, <span class="number">18</span>, <span class="number">54</span>, <span class="number">90</span>, <span class="number">27</span>, <span class="number">63</span>&#125;</span><br></pre></td></tr></table></figure>
<h4 id="生成器推导式（不直接生成元组）"><a href="#生成器推导式（不直接生成元组）" class="headerlink" title="生成器推导式（不直接生成元组）"></a>生成器推导式（不直接生成元组）</h4><p>很多同学可能会问：“都有推导式，元组有没有？”，能不能用小括号呢？</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>(x <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>,<span class="number">100</span>) <span class="keyword">if</span> x%<span class="number">9</span>==<span class="number">0</span>)</span><br><span class="line">&lt;generator <span class="built_in">object</span> &lt;genexpr&gt; at <span class="number">0x0000000002BD3048</span>&gt;</span><br></pre></td></tr></table></figure>
<p>我们发现提示的是“一个生成器对象”。显然，<strong>元组是没有推导式的</strong>。</p>
<p>一个生成器只能运行一次。第一次迭代可以得到数据，第二次迭代发现数据已经没有了。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">gnt = (x <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>,<span class="number">100</span>) <span class="keyword">if</span> x%<span class="number">9</span>==<span class="number">0</span>)</span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> gnt:</span><br><span class="line">    <span class="built_in">print</span>(x,end=<span class="string">&#x27; &#x27;</span>)</span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> gnt:</span><br><span class="line">    <span class="built_in">print</span>(x,end=<span class="string">&#x27; &#x27;</span>)</span><br></pre></td></tr></table></figure>
<h3 id="综合练习"><a href="#综合练习" class="headerlink" title="综合练习"></a>综合练习</h3><h4 id="绘制不同颜色的同心圆"><a href="#绘制不同颜色的同心圆" class="headerlink" title="绘制不同颜色的同心圆"></a>绘制不同颜色的同心圆</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311161759604.png" alt="image-20231116173335354"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 绘制不同颜色的同心圆</span></span><br><span class="line"><span class="keyword">import</span> turtle</span><br><span class="line"></span><br><span class="line">p = turtle.Pen()  <span class="comment"># 画笔对象</span></span><br><span class="line"></span><br><span class="line">radius = [x * <span class="number">10</span> <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, <span class="number">11</span>)]</span><br><span class="line">my_color = [<span class="string">&quot;red&quot;</span>, <span class="string">&quot;yellow&quot;</span>, <span class="string">&quot;black&quot;</span>, <span class="string">&quot;green&quot;</span>]</span><br><span class="line">p.width(<span class="number">4</span>)</span><br><span class="line"><span class="keyword">for</span> r, i <span class="keyword">in</span> <span class="built_in">zip</span>(radius, <span class="built_in">range</span>(<span class="built_in">len</span>(radius))):  <span class="comment"># （10，0），(20,1)</span></span><br><span class="line">    p.penup()</span><br><span class="line">    p.goto(<span class="number">0</span>, -r)</span><br><span class="line">    p.pendown()</span><br><span class="line">    p.color(my_color[i % <span class="built_in">len</span>(my_color)])</span><br><span class="line">    p.circle(r)</span><br><span class="line"></span><br><span class="line">turtle.done()  <span class="comment"># 程序执行完毕，窗口还在</span></span><br></pre></td></tr></table></figure>
<h2 id="函数和内存底层分析"><a href="#函数和内存底层分析" class="headerlink" title="函数和内存底层分析"></a>函数和内存底层分析</h2><p>函数是可重用的程序代码块。</p>
<p>函数的作用，不仅可以实现代码的复用，更能实现代码的一致性。一致性指的是，只要修改函数的代码，则所有调用该函数的地方都能得到体现。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051639821.png" alt="image-20240205163918788"></p>
<blockquote>
<p>在编写函数时，函数体中的代码写法和我们前面讲述的基本一致，只是对代码实现了封装，并增加了函数调用、传递参数、返回计算结果等内容。</p>
<p>:warning:为了让大家更容易理解，掌握的更深刻。我们也要深入内存底层进行分析。绝大多数语言内存底层都是高度相似的，这样大家掌握了这些内容也便于以后学习其他语言。</p>
</blockquote>
<h3 id="函数简介"><a href="#函数简介" class="headerlink" title="函数简介"></a>函数简介</h3><h4 id="函数-function-的基本概念"><a href="#函数-function-的基本概念" class="headerlink" title="函数(function)的基本概念"></a>函数(function)的基本概念</h4><ol>
<li>一个程序由一个一个的任务组成；函数就是代表一个任务或者一个功能(function)。</li>
<li>函数是代码复用的通用机制</li>
</ol>
<h4 id="Python函数的分类"><a href="#Python函数的分类" class="headerlink" title="Python函数的分类"></a>Python函数的分类</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051641258.png" alt="image-20240205164155796"></p>
<p>Python函数分为如下几类：</p>
<ol>
<li><p>内置函数</p>
<p>我们前面使用的 <code>str()</code> 、 <code>list()</code> 、 <code>len()</code> 等这些都是内置函数，我们可以拿来直接使用。</p>
</li>
<li><p>标准库函数</p>
<p>我们可以通过 import 语句导入库，然后使用其中定义的函数</p>
</li>
<li><p>第三方库函数</p>
<p>Python社区也提供了很多高质量的库。下载安装这些库后，也是通过 import 语句导入，然后可以使用这些第三方库的函数</p>
</li>
<li><p>用户自定义函数</p>
<p>用户自己定义的函数，显然也是开发中适应用户自身需求定义的函数。今天我们学习的就是如何自定义函数。</p>
</li>
</ol>
<h3 id="函数的定义和调用"><a href="#函数的定义和调用" class="headerlink" title="函数的定义和调用"></a>函数的定义和调用</h3><h4 id="核心要点"><a href="#核心要点" class="headerlink" title="核心要点"></a>核心要点</h4><p>Python中，定义函数的语法如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span>  <span class="title function_">函数名</span> ([参数列表]) :</span><br><span class="line"> 	<span class="string">&#x27;&#x27;&#x27;文档字符串&#x27;&#x27;&#x27;</span></span><br><span class="line"> 	函数体/若干语句</span><br></pre></td></tr></table></figure>
<p>简单定义一个函数：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">add</span>(<span class="params">a,b,c</span>):</span><br><span class="line">    <span class="string">&#x27;&#x27;&#x27;完成三个数的加法，并返回他们的和&#x27;&#x27;&#x27;</span></span><br><span class="line">    <span class="built_in">sum</span> = a+b+c</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;&#123;0&#125;、&#123;1&#125;、&#123;2&#125;三个数的和是：&#123;3&#125;&quot;</span>.<span class="built_in">format</span>(a,b,c,<span class="built_in">sum</span>))</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">sum</span></span><br><span class="line">add(<span class="number">10</span>,<span class="number">20</span>,<span class="number">30</span>)</span><br><span class="line">add(<span class="number">30</span>,<span class="number">40</span>,<span class="number">50</span>)</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311171943313.png" alt="image-20231117164127321"></p>
<p><strong>要点：</strong></p>
<ol>
<li>我们使用 <code>def</code> 来定义函数，然后就是一个空格和函数名称；<ul>
<li>Python执行 <code>def</code> 时，会创建一个函数对象，并绑定到函数名变量上。</li>
</ul>
</li>
<li>参数列表<ul>
<li>圆括号内是形式参数列表，有多个参数则使用逗号隔开</li>
<li><strong>定义时的形式参数</strong>不需要声明类型，也不需要指定函数返回值类型</li>
<li><strong>调用时的实际参数</strong>必须与形参列表一一对应</li>
</ul>
</li>
<li><code>return</code> 返回值<ul>
<li>如果函数体中包含 <code>return</code> 语句，则结束函数执行并返回值；</li>
<li>如果函数体中不包含 <code>return</code> 语句，则返回 <code>None</code> 值。</li>
</ul>
</li>
<li>调用函数之前，必须要先定义函数，即先调用 def 创建函数对象<ul>
<li>内置函数对象会自动创建</li>
<li>标准库和第三方库函数，通过 <code>import</code> 导入模块时，会执行模块中的<code>def</code>语句</li>
</ul>
</li>
</ol>
<h4 id="形参和实参"><a href="#形参和实参" class="headerlink" title="形参和实参"></a>形参和实参</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051650975.png" alt="image-20240205165030263"></p>
<p>形参和实参的要点：</p>
<ol>
<li>圆括号内是形式参数列表，有多个参数则使用逗号隔开</li>
<li><strong>定义时的形式参数</strong>不需要声明类型，也不需要指定函数返回值类型</li>
<li><strong>调用时的实际参数</strong>必须与形参列表一一对应</li>
</ol>
<p>【操作】定义一个函数，实现两个数的比较，并返回较大的值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span>  <span class="title function_">printMax</span>(<span class="params">a,b</span>):</span><br><span class="line">    <span class="string">&#x27;&#x27;&#x27;实现两个数的比较，并返回较大的值&#x27;&#x27;&#x27;</span></span><br><span class="line">    <span class="keyword">if</span> a&gt;b:</span><br><span class="line">        <span class="built_in">print</span>(a,<span class="string">&#x27;较大值&#x27;</span>)</span><br><span class="line">        <span class="keyword">return</span> a</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="built_in">print</span>(b,<span class="string">&#x27;较大值&#x27;</span>)</span><br><span class="line">        <span class="keyword">return</span> b</span><br><span class="line">printMax(<span class="number">10</span>,<span class="number">20</span>)</span><br><span class="line">printMax(<span class="number">30</span>,<span class="number">5</span>)</span><br></pre></td></tr></table></figure>
<p>上面的 <code>printMax</code> 函数中，在定义时写的 <code>printMax(a,b)</code> 。 a 和 b 称为“形式参数”，简称“形参”。也就是说，形式参数是在定义函数时使用的。 形式参数的命名要<strong>符合“标识符”命名规则</strong>。在调用函数时，传递的参数称为“实际参数”，简称“实参”。上面代码中， <code>printMax(10,20)</code> ， 10 和 20 就是实际参数。</p>
<h4 id="文档字符串-函数的注释"><a href="#文档字符串-函数的注释" class="headerlink" title="文档字符串(函数的注释)"></a>文档字符串(函数的注释)</h4><p>程序的可读性最重要，一般建议在函数体开始的部分附上函数定义说明，这就是“文档字符串”，也有人成为“函数的注释”。我们通过三</p>
<p>个<strong>单引号</strong>或者<strong>三个双引号</strong>来实现，中间可以加入多行文字进行说明。</p>
<p>【操作】测试文档字符串的使用</p>
<p>我们调用 <code>help(函数名)</code> 可打印输出函数的文档字符串。</p>
<p>我们也可以通过 <code>函数名.__doc__</code> 直接获取到函数的文档字符串，自己进行打印。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">printMax</span>(<span class="params">a, b</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    求两个数较大的数</span></span><br><span class="line"><span class="string">    :param a: 一个参数</span></span><br><span class="line"><span class="string">    :param b: 一个参数</span></span><br><span class="line"><span class="string">    :return: 返回较大的数</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="built_in">help</span>(printMax)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;print(printMax.__doc__)  &quot;</span>, printMax.__doc__)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">Help on function printMax in module __main__:</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">printMax(a, b)</span></span><br><span class="line"><span class="string">    求两个数较大的数</span></span><br><span class="line"><span class="string">    :param a: 一个参数</span></span><br><span class="line"><span class="string">    :param b: 一个参数</span></span><br><span class="line"><span class="string">    :return: 返回较大的数</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot; </span></span><br><span class="line"><span class="string">print(printMax.__doc__)   </span></span><br><span class="line"><span class="string">    求两个数较大的数</span></span><br><span class="line"><span class="string">    :param a: 一个参数</span></span><br><span class="line"><span class="string">    :param b: 一个参数</span></span><br><span class="line"><span class="string">    :return: 返回较大的数</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h4 id="返回值详解"><a href="#返回值详解" class="headerlink" title="返回值详解"></a>返回值详解</h4><p><code>return</code> 返回值要点：</p>
<ol>
<li>如果函数体中包含 <code>return</code> 语句，则结束函数执行并返回值</li>
<li>如果函数体中不包含 <code>return</code> 语句，则返回 <code>None</code> 值</li>
<li>要返回多个值，使用列表、元组、字典、集合将多个值“存起来”即可</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">printShape</span>(<span class="params">n</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    返回一个列表</span></span><br><span class="line"><span class="string">    :param n:</span></span><br><span class="line"><span class="string">    :return:</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    s1 = <span class="string">&quot;#&quot;</span> * n</span><br><span class="line">    s2 = <span class="string">&quot;$&quot;</span> * n</span><br><span class="line">    <span class="keyword">return</span> [s1, s2]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">s = printShape(<span class="number">5</span>)</span><br><span class="line"><span class="built_in">print</span>(s)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">[&#x27;#####&#x27;, &#x27;$$$$$&#x27;]</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="函数也是对象，内存底层分析"><a href="#函数也是对象，内存底层分析" class="headerlink" title="函数也是对象，内存底层分析"></a>函数也是对象，内存底层分析</h3><p>==Python中，”一切都是对象”==。实际上，执行def定义函数后，系统就创建了相应的==函数对象==。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">print_star</span>(<span class="params">n</span>):                </span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;*&quot;</span>*n)</span><br><span class="line">    </span><br><span class="line"><span class="built_in">print</span>(print_star)</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">id</span>(print_star))</span><br><span class="line">c = print_star</span><br><span class="line">c(<span class="number">3</span>)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">&lt;function print_star at 0x0000000002BB8620&gt;</span></span><br><span class="line"><span class="string">45844000</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311171943319.png" alt="image-20231117170506090"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311171943320.png" alt="image-20231117170556762"></p>
<ol>
<li>显然，我们可以看出变量 <code>c</code> 和 <code>print_star</code> 都是指向了同一个函数对象。因此，执行 <code>c(3)</code> 和执行<code>print_star(3)</code> 的效果是完全一致的。</li>
<li>Python中，圆括号意味着调用函数。在没有圆括号的情况下，Python会把函数当做普通对象。</li>
</ol>
<p>与此核心原理类似，我们也可以做如下操作：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">zhengshu = <span class="built_in">int</span></span><br><span class="line">zhengshu(<span class="string">&quot;234&quot;</span>)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>显然，我们将内置函数对象 int() 赋值给了变量 zhengshu ，这样zhengshu 和 int 都是指向了同一个内置函数对象。</p>
<p>:warning:当然，此处仅限于原理性讲解，实际开发中没必要这么做。</p>
</blockquote>
<h3 id="变量的作用域-全局变量和局部变量"><a href="#变量的作用域-全局变量和局部变量" class="headerlink" title="变量的作用域(全局变量和局部变量)"></a>变量的作用域(全局变量和局部变量)</h3><p>变量起作用的范围称为变量的作用域，不同作用域内同名变量之间互不影响。变量分为：全局变量、局部变量。</p>
<h4 id="全局变量"><a href="#全局变量" class="headerlink" title="全局变量"></a>全局变量</h4><ol>
<li>在函数和类定义之外声明的变量。作用域为定义的模块，从定义位置开始直到模块结束。</li>
<li>全局变量降低了函数的通用性和可读性。应尽量避免全局变量的使用。</li>
<li>要在函数内改变全局变量的值，使用 <code>global</code> 声明一下</li>
</ol>
<h4 id="局部变量"><a href="#局部变量" class="headerlink" title="局部变量"></a>局部变量</h4><ol>
<li>在函数体中（包含形式参数）声明的变量。</li>
<li>局部变量的引用比全局变量快，优先考虑使用</li>
<li>如果局部变量和全局变量同名，则在函数内隐藏全局变量，只使用同名的局部变量</li>
</ol>
<p>【操作】 输出局部变量和全局变量</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="number">100</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>(<span class="params">a, b, c</span>):</span><br><span class="line">    <span class="built_in">print</span>(a, b, c)</span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">locals</span>())    <span class="comment"># 打印输出的局部变量</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;#&quot;</span> * <span class="number">20</span>)</span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">globals</span>())   <span class="comment"># 打印输出的全局变量</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">f1(<span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">2 3 4</span></span><br><span class="line"><span class="string">&#123;&#x27;a&#x27;: 2, &#x27;b&#x27;: 3, &#x27;c&#x27;: 4&#125;</span></span><br><span class="line"><span class="string">####################</span></span><br><span class="line"><span class="string">&#123;&#x27;__name__&#x27;: &#x27;__main__&#x27;, &#x27;__doc__&#x27;: None, &#x27;__package__&#x27;: None, &#x27;__loader__&#x27;: &lt;_frozen_importlib_external.SourceFileLoader object at 0x0000023373C06CD0&gt;, &#x27;__spec__&#x27;: None, &#x27;__annotations__&#x27;: &#123;&#125;, &#x27;__builtins__&#x27;: &lt;module &#x27;builtins&#x27; (built-in)&gt;, &#x27;__file__&#x27;: &#x27;D:\\2022百战Python\\Python基础\\函数和内存分析\\practice.py&#x27;, &#x27;__cached__&#x27;: None, &#x27;a&#x27;: 100, &#x27;f1&#x27;: &lt;function f1 at 0x0000023374387E50&gt;&#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h4 id="局部变量和全局变量效率测试"><a href="#局部变量和全局变量效率测试" class="headerlink" title="局部变量和全局变量效率测试"></a>局部变量和全局变量效率测试</h4><p>==局部变量的查询和访问速度比全局变量快，优先考虑使用，尤其是在循环的时候。==</p>
<p>==在特别强调效率的地方或者循环次数较多的地方，可以通过将全局变量转为局部变量提高运行速度。==</p>
<h3 id="参数的传递"><a href="#参数的传递" class="headerlink" title="参数的传递"></a>参数的传递</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051704370.png" alt="image-20240205170408020"></p>
<p>函数的参数传递本质上就是：从实参到形参的赋值操作。Python中“一切皆对象”，所有的赋值操作都是“引用的赋值”。所以，Python中参数的传递都是“引用传递”，不是“值传递”。</p>
<p>具体操作时分为两类：</p>
<ol>
<li>对“可变对象”进行“写操作”，直接作用于原对象本身。</li>
<li>对“不可变对象”进行“写操作”，会产生一个新的“对象空间”，并用新的值填充这块空间。</li>
</ol>
<blockquote>
<p>:warning:</p>
<p>可变对象有：</p>
<p>==字典、列表、集合==、自定义的对象等</p>
<p>不可变对象有：</p>
<p>数字、==字符串、元组、function==等</p>
</blockquote>
<h4 id="传递可变对象的引用"><a href="#传递可变对象的引用" class="headerlink" title="传递可变对象的引用"></a>传递可变对象的引用</h4><p>传递参数是可变对象（例如：<code>列表</code>、<code>字典</code>、<code>集合</code>、自定义的其他可变对象等），实际传递的还是对象的引用。在函数体中不创建新的对象拷贝，而是可以直接修改所传递的对象。</p>
<p>【操作】参数传递：传递可变对象的引用</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">b = [<span class="number">10</span>,<span class="number">20</span>]</span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f2</span>(<span class="params">m</span>):</span><br><span class="line">  	<span class="built_in">print</span>(<span class="string">&quot;m:&quot;</span>,<span class="built_in">id</span>(m))       <span class="comment"># b和m是同一个对象</span></span><br><span class="line">    m.append(<span class="number">30</span>)            <span class="comment"># 由于m是可变对象，不创建对象拷贝，直接修改这个对象</span></span><br><span class="line"></span><br><span class="line">f2(b)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;b:&quot;</span>,<span class="built_in">id</span>(b))</span><br><span class="line"><span class="built_in">print</span>(b)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">m: 45765960</span></span><br><span class="line"><span class="string">b: 45765960</span></span><br><span class="line"><span class="string">[10, 20, 30]</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h4 id="传递不可变对象的引用"><a href="#传递不可变对象的引用" class="headerlink" title="传递不可变对象的引用"></a>传递不可变对象的引用</h4><p>传递参数是不可变对象（例如： <code>int</code> 、 <code>float</code> 、<code>字符串</code>、<code>元组</code>、<code>布尔值</code>），实际传递的还是对象的引用。在”赋值操作”时，由于不可变对象无法修改，系统会新创建一个对象。</p>
<p>【操作】参数传递：传递不可变对象的引用</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="number">100</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>(<span class="params">n</span>):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;n:&quot;</span>,<span class="built_in">id</span>(n))        <span class="comment"># 传递进来的是a对象的地址</span></span><br><span class="line">    n = n+<span class="number">200</span>                <span class="comment"># 由于a是不可变对象，因此创建新的对象n</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;n:&quot;</span>,<span class="built_in">id</span>(n))        <span class="comment">#n 已经变成了新的对象</span></span><br><span class="line">    <span class="built_in">print</span>(n)</span><br><span class="line">f1(a)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;a:&quot;</span>,<span class="built_in">id</span>(a))</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">n: 1663816464</span></span><br><span class="line"><span class="string">n: 46608592</span></span><br><span class="line"><span class="string">300</span></span><br><span class="line"><span class="string">a: 1663816464</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p>显然，通过 <code>id</code> 值我们可以看到 <code>n</code> 和 <code>a</code> 一开始是同一个对象。给<code>n</code>赋值后，<code>n</code>是新的对象。</p>
<h4 id="浅拷贝和深拷贝"><a href="#浅拷贝和深拷贝" class="headerlink" title="浅拷贝和深拷贝"></a>浅拷贝和深拷贝</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051712474.png" alt="image-20240205171232805"></p>
<ol>
<li><strong>浅拷贝</strong>：==拷贝对象，但不拷贝子对象的内容，只是拷贝子对象的引用。==</li>
<li><strong>深拷贝</strong>：==拷贝对象，并且会连子对象的内存也全部（递归）拷贝一份，对子对象的修改不会影响源对象==</li>
</ol>
<h4 id="传递不可变对象包含的子对象是可变的情况"><a href="#传递不可变对象包含的子对象是可变的情况" class="headerlink" title="传递不可变对象包含的子对象是可变的情况"></a>传递不可变对象包含的子对象是可变的情况</h4><p>传递不可变对象时，不可变对象里面包含的子对象是可变的。则方法内修改了这个可变对象，源对象也发生了变化。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">a = (<span class="number">10</span>,<span class="number">20</span>,[<span class="number">5</span>,<span class="number">6</span>])</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;a:&quot;</span>,<span class="built_in">id</span>(a))</span><br><span class="line"><span class="keyword">def</span> <span class="title function_">test01</span>(<span class="params">m</span>):</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;m:&quot;</span>,<span class="built_in">id</span>(m))</span><br><span class="line">    m[<span class="number">2</span>][<span class="number">0</span>] = <span class="number">888</span></span><br><span class="line">    <span class="built_in">print</span>(m)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;m:&quot;</span>,<span class="built_in">id</span>(m))</span><br><span class="line">test01(a)</span><br><span class="line"><span class="built_in">print</span>(a)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">a: 41611632</span></span><br><span class="line"><span class="string">m: 41611632</span></span><br><span class="line"><span class="string">(10, 20, [888, 6])</span></span><br><span class="line"><span class="string">m: 41611632</span></span><br><span class="line"><span class="string">(10, 20, [888, 6])</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="参数的几种类型"><a href="#参数的几种类型" class="headerlink" title="参数的几种类型"></a>参数的几种类型</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051716149.png" alt="image-20240205171609469"></p>
<h4 id="位置参数"><a href="#位置参数" class="headerlink" title="位置参数"></a>位置参数</h4><p>函数调用时，实参默认按位置顺序传递，需要个数和形参匹配。按位置传递的参数，称为：“位置参数”。</p>
<p>【操作】测试位置参数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>(<span class="params">a,b,c</span>):</span><br><span class="line">    <span class="built_in">print</span>(a,b,c)</span><br><span class="line">f1(<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>)</span><br><span class="line">f1(<span class="number">2</span>,<span class="number">3</span>)     <span class="comment"># 报错，位置参数不匹配</span></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">2 3 4</span></span><br><span class="line"><span class="string">Traceback (most recent call last):</span></span><br><span class="line"><span class="string">  File &quot;E:\PythonExec\if_test01.py&quot;, line 5,</span></span><br><span class="line"><span class="string">in &lt;module&gt;</span></span><br><span class="line"><span class="string">    f1(2,3)</span></span><br><span class="line"><span class="string">TypeError: f1() missing 1 required positional</span></span><br><span class="line"><span class="string">argument: &#x27;c</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h4 id="默认值参数"><a href="#默认值参数" class="headerlink" title="默认值参数"></a>默认值参数</h4><p>我们可以为某些参数设置默认值，这样这些参数在传递时就是可选的。称为“默认值参数”。默认值参数放到位置参数后面。</p>
<p>【操作】测试默认值参数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>(<span class="params">a,b,c=<span class="number">10</span>,d=<span class="number">20</span></span>):   <span class="comment"># 默认值参数必须位于普通位置参数后面</span></span><br><span class="line">    <span class="built_in">print</span>(a,b,c,d)</span><br><span class="line">f1(<span class="number">8</span>,<span class="number">9</span>)</span><br><span class="line">f1(<span class="number">8</span>,<span class="number">9</span>,<span class="number">19</span>)</span><br><span class="line">f1(<span class="number">8</span>,<span class="number">9</span>,<span class="number">19</span>,<span class="number">29</span>)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">8 9 10 20</span></span><br><span class="line"><span class="string">8 9 19 20</span></span><br><span class="line"><span class="string">8 9 19 29</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h4 id="命名参数-关键字参数"><a href="#命名参数-关键字参数" class="headerlink" title="命名参数(关键字参数)"></a>命名参数(关键字参数)</h4><p>我们也可以按照形参的名称传递参数，称为“命名参数”，也称“关键字参数”。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>(<span class="params">a,b,c</span>):</span><br><span class="line">    <span class="built_in">print</span>(a,b,c)</span><br><span class="line">f1(<span class="number">8</span>,<span class="number">9</span>,<span class="number">19</span>)          <span class="comment"># 位置参数</span></span><br><span class="line">f1(c=<span class="number">10</span>,a=<span class="number">20</span>,b=<span class="number">30</span>)  <span class="comment"># 命名参数</span></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">8 9 19</span></span><br><span class="line"><span class="string">20 30 10</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h4 id="可变参数"><a href="#可变参数" class="headerlink" title="可变参数"></a>可变参数</h4><p>可变参数指的是“可变数量的参数”。分两种情况：</p>
<ol>
<li><code>*param</code> （一个星号），将多个参数收集到一个“元组”对象中。 </li>
<li><code>**param</code> （两个星号），将多个参数收集到一个“字典”对象中。</li>
</ol>
<p>【操作】测试可变参数处理（元组、字典两种方式）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>(<span class="params">a,b,*c</span>):</span><br><span class="line">    <span class="built_in">print</span>(a,b,c)   </span><br><span class="line">f1(<span class="number">8</span>,<span class="number">9</span>,<span class="number">19</span>,<span class="number">20</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">f2</span>(<span class="params">a,b,**c</span>):</span><br><span class="line">    <span class="built_in">print</span>(a,b,c)</span><br><span class="line">f2(<span class="number">8</span>,<span class="number">9</span>,name=<span class="string">&#x27;gaoqi&#x27;</span>,age=<span class="number">18</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span>  <span class="title function_">f3</span>(<span class="params">a,b,*c,**d</span>):</span><br><span class="line">    <span class="built_in">print</span>(a,b,c,d)</span><br><span class="line">f3(<span class="number">8</span>,<span class="number">9</span>,<span class="number">20</span>,<span class="number">30</span>,name=<span class="string">&#x27;gaoqi&#x27;</span>,age=<span class="number">18</span>)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">8 9 (19, 20)</span></span><br><span class="line"><span class="string">8 9 &#123;&#x27;name&#x27;: &#x27;gaoqi&#x27;, &#x27;age&#x27;: 18&#125;</span></span><br><span class="line"><span class="string">8 9 (20, 30) &#123;&#x27;name&#x27;: &#x27;gaoqi&#x27;, &#x27;age&#x27;: 18&#125;</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h4 id="强制命名参数"><a href="#强制命名参数" class="headerlink" title="强制命名参数"></a>强制命名参数</h4><p>在带星号的“可变参数”后面增加新的参数，必须在调用的时候“强制命名参数”。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>(<span class="params">*a,b,c</span>):</span><br><span class="line">    <span class="built_in">print</span>(a,b,c)</span><br><span class="line"><span class="comment">#f1(2,3,4)   	# 会报错。由于a是可变参数，将2,3,4全部收集。造成b和c没有赋值。</span></span><br><span class="line">f1(<span class="number">2</span>,b=<span class="number">3</span>,c=<span class="number">4</span>)</span><br></pre></td></tr></table></figure>
<h3 id="lambda表达式和匿名函数"><a href="#lambda表达式和匿名函数" class="headerlink" title="lambda表达式和匿名函数"></a>lambda表达式和匿名函数</h3><p><code>lambda</code> 表达式可以用来声明匿名函数。 <code>lambda</code> 函数是一种简单的、在同一行中定义函数的方法。 <code>lambda</code> 函数实际生成了一个函数对象。</p>
<p><code>lambda</code> 表达式只允许包含一个表达式，不能包含复杂语句，该表达式的计算结果就是函数的返回值。</p>
<p><code>lambda</code> 表达式的基本语法如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">lambda</span>  arg1,arg2,arg3... :  &lt;表达式&gt;</span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>arg1</code> <code>arg2</code> <code>arg3</code> 为函数的参数。<code>&lt;表达式&gt;</code>相当于函数体。运算结果是：表达式的运算结果。</p>
</blockquote>
<p>【操作】lambda表达式使用</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">f = <span class="keyword">lambda</span> a, b, c: a + b + c</span><br><span class="line"><span class="built_in">print</span>(f)</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">id</span>(f))</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(f))</span><br><span class="line"><span class="built_in">print</span>(f(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>))</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">&lt;function &lt;lambda&gt; at 0x000001AF907F7E50&gt;</span></span><br><span class="line"><span class="string">1853555179088</span></span><br><span class="line"><span class="string">&lt;class &#x27;function&#x27;&gt;</span></span><br><span class="line"><span class="string">6</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">g = [<span class="keyword">lambda</span> a: a * <span class="number">2</span>, <span class="keyword">lambda</span> b: b * <span class="number">4</span>, <span class="keyword">lambda</span> c: c * <span class="number">8</span>]</span><br><span class="line"><span class="built_in">print</span>(g[<span class="number">0</span>](<span class="number">1</span>), g[<span class="number">1</span>](<span class="number">2</span>), g[<span class="number">2</span>](<span class="number">3</span>))</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">2 8 24</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="eval-函数"><a href="#eval-函数" class="headerlink" title="eval()函数"></a>eval()函数</h3><p>功能：将字符串 <code>str</code> 当成有效的表达式来求值并返回计算结果。</p>
<p>语法： <code>eval(source[, globals[, locals]]) -&gt; value</code></p>
<p>参数：</p>
<ol>
<li><code>source</code> ：一个Python表达式或函数 <code>compile()</code> 返回的代码对象 </li>
<li><code>globals</code> ：可选。必须是 <code>dictionary</code> </li>
<li><code>locals</code> ：可选。任意映射对象 </li>
</ol>
<blockquote>
<p>:warning:<code>eval函数</code>会将字符串当做语句来执行，因此会被注入安全隐患。比如：字符串中含有删除文件的语句。那就麻烦大了。因此，使用时候，要慎重！！！</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">s = <span class="string">&quot;print(&#x27;abcd&#x27;)&quot;</span></span><br><span class="line"><span class="built_in">eval</span>(s)   <span class="comment"># eval会将字符串当成语句来执行</span></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;abcd&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">a = <span class="number">10</span></span><br><span class="line">b = <span class="number">20</span></span><br><span class="line">c = <span class="built_in">eval</span>(<span class="string">&quot;a+b&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(c)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;30&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">dict1 = <span class="built_in">dict</span>(a=<span class="number">100</span>, b=<span class="number">200</span>)</span><br><span class="line">d = <span class="built_in">eval</span>(<span class="string">&quot;a+b&quot;</span>, dict1)</span><br><span class="line"><span class="built_in">print</span>(d)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;300&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="递归函数"><a href="#递归函数" class="headerlink" title="递归函数"></a>递归函数</h3><ol>
<li>递归(recursion)是一种常见的算法思路，在很多算法中都会用到。比如：深度优先搜索（DFS:Depth First Search）等。</li>
<li>递归的基本思想就是“自己调用自己”</li>
</ol>
<p>递归函数指的是：自己调用自己的函数，在函数体内部直接或间接的自己调用自己。每个递归函数必须包含两个部分：</p>
<ol>
<li><p>终止条件</p>
<p>表示递归什么时候结束。一般用于返回值，不再调用自己。</p>
</li>
<li><p>递归步骤</p>
<p>把第n步的值和第n-1步相关联。</p>
</li>
</ol>
<blockquote>
<p>:warning:递归函数由于会创建大量的函数对象、过量的消耗内存和运算能力。在处理大量数据时，谨慎使用。</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">my_recursion</span>(<span class="params">n</span>):</span><br><span class="line">  	<span class="built_in">print</span>(<span class="string">&quot;start:&quot;</span> + <span class="built_in">str</span>(n))</span><br><span class="line">    <span class="keyword">if</span> n == <span class="number">1</span>:</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;recursion over!&quot;</span>)</span><br><span class="line">   	<span class="keyword">else</span>:</span><br><span class="line">       	my_recursion(n - <span class="number">1</span>)</span><br><span class="line"></span><br><span class="line">   	<span class="built_in">print</span>(<span class="string">&quot;end:&quot;</span> + <span class="built_in">str</span>(n))</span><br><span class="line"></span><br><span class="line">my_recursion(<span class="number">3</span>)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">start:3</span></span><br><span class="line"><span class="string">start:2</span></span><br><span class="line"><span class="string">start:1</span></span><br><span class="line"><span class="string">recursion over!</span></span><br><span class="line"><span class="string">end:1</span></span><br><span class="line"><span class="string">end:2</span></span><br><span class="line"><span class="string">end:3</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311171943343.png" alt="image-20231117185027038"></p>
<p>【操作】 使用递归函数计算阶乘(factorial)</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">factorial</span>(<span class="params">n</span>):</span><br><span class="line">    <span class="keyword">if</span> n == <span class="number">1</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="number">1</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> n * factorial(n - <span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(factorial(<span class="number">5</span>))</span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311171943344.png" alt="image-20231117185357907"></p>
<h3 id="嵌套函数-内部函数"><a href="#嵌套函数-内部函数" class="headerlink" title="嵌套函数(内部函数)"></a>嵌套函数(内部函数)</h3><p><strong>嵌套函数：在函数内部定义的函数!</strong></p>
<p>一般在什么情况下使用嵌套函数？</p>
<ol>
<li><p>封装-数据隐藏 </p>
<p>外部无法访问“嵌套函数”。</p>
</li>
<li><p>贯彻DRY(Don’t Repeat Yourself)原则</p>
</li>
<li><p>嵌套函数，可以让我们在函数内部避免重复代码。</p>
</li>
<li><p>闭包（后面会讲解）</p>
</li>
</ol>
<h3 id="nonlocal和global关键字"><a href="#nonlocal和global关键字" class="headerlink" title="nonlocal和global关键字"></a>nonlocal和global关键字</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051743134.png" alt="image-20240205174327181"></p>
<p><code>nonlocal</code> 用来在内部函数中，声明外层的局部变量。</p>
<p><code>global</code> 函数内声明全局变量，然后才使用全局变量</p>
<h3 id="LEGB规则"><a href="#LEGB规则" class="headerlink" title="LEGB规则"></a>LEGB规则</h3><p>Python在查找“名称”时，是按照LEGB规则查找的：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051744783.png" alt="image-20240205174442308"></p>
<p><code>Local</code> 指的就是函数或者类的方法内部</p>
<p><code>Enclosed</code> 指的是嵌套函数（一个函数包裹另一个函数，闭包）</p>
<p><code>Global</code> 指的是模块中的全局变量</p>
<p><code>Built in</code> 指的是Python为自己保留的特殊名称</p>
<blockquote>
<p>如果某个 <code>name</code> 映射在局部 <code>local</code> 命名空间中没有找到，接下来就会在闭包作用域 <code>enclosed</code> 进行搜索，如果闭包作用域也没有找到，Python就会到全局 <code>global</code> 命名空间中进行查找，最后会在内建<code>built-in</code> 命名空间搜索 （如果一个名称在所有命名空间中都没有找到，就会产生一个 <code>NameError</code> ）</p>
</blockquote>
<h2 id="面向对象"><a href="#面向对象" class="headerlink" title="面向对象"></a>面向对象</h2><h3 id="面向对象简介"><a href="#面向对象简介" class="headerlink" title="面向对象简介"></a>面向对象简介</h3><p>Python完全采用了面向对象的思想，是真正面向对象的编程语言，完全支持面向对象的基本功能，例如：继承、多态、封装等。</p>
<p>==Python中，一切皆对象==。我们在前面学习的数据类型、函数等，都是对象。</p>
<blockquote>
<ul>
<li>面向对象（Object oriented Programming，OOP）编程的思想主要是针对大型软件设计而来的。</li>
<li>面向对象编程使程序的扩展性更强、可读性更好，使编程可以像搭积木一样简单。</li>
<li>面向对象编程将数据和操作数据相关的方法封装到对象中，组织代码和数据的方式更加接近人的思维，从而大大提高了编程的效率。</li>
</ul>
<p>❤️Python支持面向过程、面向对象、函数式编程等多种编程范式。</p>
</blockquote>
<h3 id="面向过程和面向对象思想"><a href="#面向过程和面向对象思想" class="headerlink" title="面向过程和面向对象思想"></a>面向过程和面向对象思想</h3><h4 id="面向过程和面向对象的区别"><a href="#面向过程和面向对象的区别" class="headerlink" title="面向过程和面向对象的区别"></a>面向过程和面向对象的区别</h4><p>面向过程和面向对象都是对软件分析、设计和开发的一种思想，它指导着人们以不同的方式去分析、设计和开发软件。</p>
<p>==C语言是一种典型的面向过程语言，Java是一种典型的面向对象语言。==</p>
<h4 id="面向过程是什么？"><a href="#面向过程是什么？" class="headerlink" title="面向过程是什么？"></a>面向过程是什么？</h4><p>面向过程适合简单、不需要协作的事务，重点关注如何执行。面向过程时，我们首先思考“怎么按步骤实现？”。</p>
<p>比如，如何开车？我们很容易就列出实现步骤：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051749761.png" alt="image-20240205174928790"></p>
<h4 id="面向对象是什么？"><a href="#面向对象是什么？" class="headerlink" title="面向对象是什么？"></a>面向对象是什么？</h4><p>面向对象(Oriented-Object)思想更契合人的思维模式。我们首先思考的是”怎么设计这个事物？”。比如思考造车，我们就会先思考“车怎么设计？”，而不是“怎么按步骤造车的问题”。这就是思维方式的转变。天然的，我们就会从“车由什么组成”开始思考：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051751321.png" alt="image-20240205175117899"></p>
<p>为了协作，我们找轮胎厂完成制造轮胎的步骤，发动机厂完成制造发动机的步骤；这样，发现大家可以同时进行车的制造，最终进行组装，大大提高了效率。具体到轮胎厂的一个流水线操作，仍然是有步骤的，还是离不开执行者、离不开面向过程！</p>
<blockquote>
<p>面向对象可以帮助我们从宏观上把握、从整体上分析整个系统。但是，具体到实现部分的微观操作（就是一个个方法），仍然需要面向过程的思路去处理。</p>
<p>我们干万不要把面向过程和面向对象对立起来。他们是相辅相成的。==面向对象离不开面向过程！==</p>
</blockquote>
<h4 id="面向对象和面向过程总结"><a href="#面向对象和面向过程总结" class="headerlink" title="面向对象和面向过程总结"></a>面向对象和面向过程总结</h4><p>①都是解决问题的思维方式，都是代码组织的方式。</p>
<p>②==面向过程是一种“执行者思维”==，解决简单问题可以使用面向过程</p>
<p>③==面向对象是一种“设计者思维”==，解决复杂、需要协作的问题可以使用面向对象</p>
<blockquote>
<p>面向对象离不开面向过程：</p>
<ul>
<li>宏观上：通过面向对象进行整体设计</li>
<li>微观上：执行和处理数据，仍然是面向过程</li>
</ul>
</blockquote>
<h3 id="对象进化的小故事"><a href="#对象进化的小故事" class="headerlink" title="对象进化的小故事"></a>对象进化的小故事</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311172219984.png" alt="image-20231117195725002"></p>
<h3 id="类的定义"><a href="#类的定义" class="headerlink" title="类的定义"></a>类的定义</h3><p>类可以看做是一个模版，或者图纸，系统根据类的定义来造出对象。我们要造一个汽车，怎么样造？类就是这个图纸，规定了汽车的详细信息，然后根据图纸将汽车造出来。</p>
<blockquote>
<p>类：我们叫做<code>class</code>。对象：我们叫做<code>object</code>,<code>instance</code>(实例)。以后我们说某个类的对象，某个类的实例。是一样的意思。</p>
</blockquote>
<p>我们把对象比作一个“饼干”，类就是制造这个饼干的“模具”。</p>
<h4 id="属性和方法"><a href="#属性和方法" class="headerlink" title="属性和方法"></a>属性和方法</h4><p>我们通过类定义数据类型的属性（数据）和方法（行为）,也就是说，“类将行为和状态打包在一起”。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051754172.png" alt="image-20240205175450838"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051755456.png" alt="image-20240205175508133"></p>
<blockquote>
<p>从一个类创建对象时，每个对象会共享这个类的行为（类中定义的方法），但会有自己的属性值（不共享状态）。更具体一点：“方法代码是共享的，属性数据不共享”。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051755634.png" alt="image-20240205175550650"></p>
<p>Python中，”一切皆对象”。类也称为“==类对像==”，类的实例也称为“实例对象”。</p>
</blockquote>
<p>定义类的语法格式如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span>  <span class="title class_">类名</span>：</span><br><span class="line">	类体</span><br></pre></td></tr></table></figure>
<p>要点如下：</p>
<p>①类名必须符合“标识符”的规则；一般规定，==首字母大写，多个单词使用“驼峰原则”==。</p>
<p>②类体中我们可以定义属性和方法</p>
<p>③属性用来描述数据，方法（即函数）用来描述这些数据相关的操作</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, score</span>):  <span class="comment"># self参数是必须有的</span></span><br><span class="line">        self.name = name              <span class="comment"># 实例属性</span></span><br><span class="line">        self.score = score            <span class="comment"># 实例属性</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_score</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;&#123;0&#125;的分数是&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(self.name, self.score))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">s1 = Student(<span class="string">&quot;john&quot;</span>, <span class="number">61</span>)  <span class="comment"># 自动调用__init__()方法</span></span><br><span class="line"><span class="built_in">print</span>(s1.name, s1.score)</span><br><span class="line">s1.say_score()</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">john 61</span></span><br><span class="line"><span class="string">john的分数是61</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h4 id="对象完整内存结构"><a href="#对象完整内存结构" class="headerlink" title="对象完整内存结构"></a>对象完整内存结构</h4><p>类是抽象的，也称之为“对象的模板”。我们需要通过类这个模板，创建类的实例对象，然后才能使用类定义的功能。</p>
<p>我们前面说过一个Python对象包含三个部分： <code>id</code> （identity识别码）、 <code>type</code> （对象类型）、 <code>value</code> （对象的值）。</p>
<p>现在，我们可以更进一步的说，一个Python对象包含如下部分：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051757516.png" alt="image-20240205175738918"></p>
<h3 id="init-构造方法和-new-方法"><a href="#init-构造方法和-new-方法" class="headerlink" title="__init__构造方法和__new__方法"></a><code>__init__</code>构造方法和<code>__new__</code>方法</h3><p>初始化对象，我们需要定义构造函数 <code>__init__()</code> 方法。构造方法用于执行“实例对象的初始化工作”，即对象创建后，初始化当前对象的相关属性，无返回值。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051759832.png" alt="image-20240205175933233"></p>
<p>构造方法是负责初始化（装修），不是建对象(房子)</p>
<p><code>__init__()</code> <strong>构造函数</strong>的要点如下：</p>
<ol>
<li><p>名称固定，必须为：<code>__init__()</code></p>
</li>
<li><p>第一个参数固定，必须为：<code>self</code>。<code>self</code>指的就是刚刚创建好的实例对象</p>
</li>
<li><p>构造函数通常用来初始化实例对象的实例属性，如下代码就是初始化实例属性：<code>name</code>和<code>score</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, score</span>):  <span class="comment"># self参数是必须有的</span></span><br><span class="line">       self.name = name           <span class="comment"># 实例属性</span></span><br><span class="line">       self.score = score         <span class="comment"># 实例属性</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>通过“类名(参数列表)”来调用构造函数。调用后，将创建好的对象返回给相应的变量。比如：<code>s1=Student(&quot;张三&quot;,80)</code></p>
</li>
<li><p><code>__init__()</code>方法：==初始化创建好的对象==，<strong>初始化指的是：“给实例属性赋值”</strong></p>
</li>
<li><p><code>__new__()</code>方法：==用于创建对象==，但我们一般无需重定义该方法</p>
</li>
<li><p>如果我们不定义<code>__init__</code>方法，系统会提供一个默认的<code>__init__</code>方法。如果我们定义了带参的<code>__init__</code>方法，系统不创建默认的<code>__init__</code>方法</p>
</li>
</ol>
<blockquote>
<p>Python中的<code>self</code>相当于C++中的<code>self指针</code>，JAVA和C#中的<code>this</code>关键字。Python中<code>self</code>必须为构造函数的第一个参数，名字可以任意修改。但一般惯例，都叫做<code>self</code></p>
</blockquote>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311172219990.png" alt="image-20231117204441814"></p>
<h3 id="实例属性和实例方法"><a href="#实例属性和实例方法" class="headerlink" title="实例属性和实例方法"></a>实例属性和实例方法</h3><h4 id="实例属性"><a href="#实例属性" class="headerlink" title="实例属性"></a>实例属性</h4><p>实例属性是从属于实例对象的属性，也称为“实例变量”。他的使用有如下几个要点：</p>
<ol>
<li><p>实例属性一般在<code>__init__()</code>方法中通过如下代码定义：</p>
<p><code>self.实例属性名 = 初始值</code></p>
</li>
<li><p>在本类的其他实例方法中，也是通过<code>self</code>进行访问：</p>
<p><code>self.实例属性名</code></p>
</li>
<li><p>创建实例对象后，通过实例对象访问：</p>
<p><code>obj01=类名()</code>                               #创建和初始化对象，调用<code>__init__()</code>初始化属性</p>
<p><code>obj01.实例属性名 = 值</code>          #可以给已有属性赋值，也可以新加属性</p>
</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self,name,score</span>):</span><br><span class="line">        self.name = name   <span class="comment"># 增加name属性</span></span><br><span class="line">        self.score = score <span class="comment"># 增加score属性</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_score</span>(<span class="params">self</span>):</span><br><span class="line">        self.age = <span class="number">18</span>      <span class="comment"># 增加age属性</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;&#123;0&#125;的分数是&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(self.name,self.score))</span><br><span class="line">s1 = Student(<span class="string">&quot;张三&quot;</span>,<span class="number">80</span>)</span><br><span class="line">s1.say_score()</span><br><span class="line"><span class="built_in">print</span>(s1.age)</span><br><span class="line">s1.salary = <span class="number">3000</span>           <span class="comment"># s1对象增加salary属性</span></span><br><span class="line">s2 = Student(<span class="string">&quot;李四&quot;</span>,<span class="number">90</span>)</span><br><span class="line">s2.say_score()</span><br><span class="line"><span class="built_in">print</span>(s2.age)</span><br></pre></td></tr></table></figure>
<h4 id="实例方法"><a href="#实例方法" class="headerlink" title="实例方法"></a>实例方法</h4><p>实例方法是从属于实例对象的方法。实例方法的定义格式如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">方法名</span>(<span class="params">self [, 形参列表]</span>):</span><br><span class="line">	函数体</span><br></pre></td></tr></table></figure>
<p>方法的调用格式如下：</p>
<p>​                        <code>对象.方法名([实参列表])</code></p>
<p>要点：</p>
<ol>
<li><p>定义实例方法时，第一个参数必须为<code>self</code>。和前面一样，<code>self</code>指当前的实例对象。</p>
</li>
<li><p>调用实例方法时，不需要也不能给<code>self</code>传参。<code>self</code>由解释器自动传参</p>
</li>
</ol>
<h4 id="函数和方法的区别"><a href="#函数和方法的区别" class="headerlink" title="函数和方法的区别"></a>函数和方法的区别</h4><ol>
<li>都是用来完成一个功能的语句块，本质一样。</li>
<li>方法调用时，通过对象来调用。方法从属于特定实例对象，普通函数没有这个特点</li>
<li>直观上看，方法定义时需要传递<code>self</code>,函数不需要</li>
</ol>
<h4 id="实例对象的方法调用本质"><a href="#实例对象的方法调用本质" class="headerlink" title="实例对象的方法调用本质"></a>实例对象的方法调用本质</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311172219991.png" alt="image-20231117210158863"></p>
<h4 id="其他操作"><a href="#其他操作" class="headerlink" title="其他操作"></a>其他操作</h4><ol>
<li><code>dir(obj)</code>可以获得对象的所有属性、方法</li>
<li><code>obj.__dict__</code>对象的属性字典</li>
<li><code>pass</code>空语句</li>
<li><code>isinstance(对象,类型)</code>判断对象”是不是”指定类型”</li>
</ol>
<h3 id="类对象、类属性、类方法、静态方法"><a href="#类对象、类属性、类方法、静态方法" class="headerlink" title="类对象、类属性、类方法、静态方法"></a>类对象、类属性、类方法、静态方法</h3><h4 id="类对象"><a href="#类对象" class="headerlink" title="类对象"></a>类对象</h4><p>我们在前面讲的类定义格式中, <code>class 类名：</code>。实际上，当解释器执行<code>class</code>语句时，就会创建一个类对象</p>
<h4 id="类属性"><a href="#类属性" class="headerlink" title="类属性"></a>类属性</h4><p>类属性是从属于“类对象”的属性，也称为“类变量”。由于，类属性从属于类对象，可以被所有实例对象共享。</p>
<p>类属性的定义方式：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">类名</span>:</span><br><span class="line">	类名变量 = 初始值</span><br></pre></td></tr></table></figure>
<p>在==类中或者类的外面==，我们可以通过：<code>类名.类变量名</code> 来读写</p>
<h4 id="内存分析实例对象和类对象创建过程（重要）"><a href="#内存分析实例对象和类对象创建过程（重要）" class="headerlink" title="内存分析实例对象和类对象创建过程（重要）"></a>内存分析实例对象和类对象创建过程（重要）</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span>:</span><br><span class="line">    school = <span class="string">&quot;HNU&quot;</span>  <span class="comment"># 类属性</span></span><br><span class="line">    count = <span class="number">0</span>       <span class="comment"># 类属性</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, score</span>):</span><br><span class="line">        self.name = name    <span class="comment"># 实例属性</span></span><br><span class="line">        self.score = score  <span class="comment"># 实例属性</span></span><br><span class="line">        Student.count = Student.count + <span class="number">1</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_score</span>(<span class="params">self</span>):    <span class="comment"># 实例方法</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;我的学校是：&quot;</span>, Student.school)</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;&#123;0&#125;的分数是&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(self.name, self.score))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">s1 = Student(<span class="string">&quot;john&quot;</span>, <span class="number">61</span>)    <span class="comment"># s1是实例对象，自动调用__init__()方法</span></span><br><span class="line">s2 = Student(<span class="string">&quot;jack&quot;</span>, <span class="number">91</span>)</span><br><span class="line">s1.say_score()</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;一共创建了&#123;0&#125;个Student对象&quot;</span>.<span class="built_in">format</span>(Student.count))</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">我的学校是： HNU</span></span><br><span class="line"><span class="string">john的分数是61</span></span><br><span class="line"><span class="string">一共创建了2个Student对象</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311172219992.png" alt="image-20231117212505195"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311172219993.png" alt="image-20231117212336356"></p>
<h4 id="类方法"><a href="#类方法" class="headerlink" title="类方法"></a>类方法</h4><p>==类方法是从属于“类对象”的方法。==类方法通过装饰器<code>@classmethod</code>来定义，格式如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@classmethod</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">类方法名</span>(<span class="params">cls [, 形参列表]</span>):</span><br><span class="line">	方法体</span><br></pre></td></tr></table></figure>
<p>要点如下：</p>
<ol>
<li><code>@classmethod</code>必须位于方法上面一行</li>
<li>第一个<code>cls</code>必须有；==<code>cls</code>指的就是“类对象”本身==</li>
<li>调用类方法格式：<code>类名.类方法名(参数列表)</code>。参数列表中，不需要也不能给<code>cls</code>传值</li>
<li><strong>类方法中访问实例属性和实例方法会导致错误</strong></li>
<li>子类继承父类方法时，传入cls是子类对象，而非父类对象（讲完继承再说）</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span>:</span><br><span class="line">    school = <span class="string">&quot;HNU&quot;</span>  <span class="comment"># 类属性</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @classmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">printSchool</span>(<span class="params">cls</span>):</span><br><span class="line">        <span class="built_in">print</span>(cls.school)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Student.printSchool()</span><br></pre></td></tr></table></figure>
<h4 id="静态方法"><a href="#静态方法" class="headerlink" title="静态方法"></a>静态方法</h4><p>Python中允许定义与”类对象”无关的方法，称为“静态方法”。</p>
<p>“静态方法”和在模块中定义普通函数没有区别，只不过“静态方法”放到了“类的名字空间里面”，需要通过“类调用”。</p>
<p>静态方法通过装饰器<code>@staticmethod</code>来定义，格式如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@staticmethod</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">静态方法名</span>(<span class="params">[形参列表]</span>):</span><br><span class="line">	方法体		</span><br></pre></td></tr></table></figure>
<p>要点如下：</p>
<ol>
<li><p><code>@staticmethod</code>必须位于方法上面一行</p>
</li>
<li><p>调用静态方法格式：<code>类名.静态方法名(参数列表)</code></p>
</li>
<li><p>静态方法中访问实例属性和实例方法会导致错误</p>
</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span>:</span><br><span class="line">    school = <span class="string">&quot;HNU&quot;</span>  <span class="comment"># 类属性</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @staticmethod</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">add</span>(<span class="params">a, b</span>):  <span class="comment"># 静态方法</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;&#123;0&#125;+&#123;1&#125;=&#123;2&#125;&quot;</span>.<span class="built_in">format</span>(a, b, a + b))</span><br><span class="line">        <span class="keyword">return</span> a+b</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Student.add(<span class="number">30</span>, <span class="number">40</span>)</span><br></pre></td></tr></table></figure>
<h3 id="del-方法-析构函数-和垃圾回收机制"><a href="#del-方法-析构函数-和垃圾回收机制" class="headerlink" title="__del__方法(析构函数)和垃圾回收机制"></a><code>__del__</code>方法(析构函数)和垃圾回收机制</h3><p>==Python实现自动的垃圾回收==</p>
<p><code>__del__()</code>称为“析构方法”，用于实现对象被销毁时所需的操作。比如：释放对象占用的资源，例如：打开的文件资源、网络连接等。</p>
<p>Python实现自动的垃圾回收，当对象没有被引用时（引用计数为0），由垃圾回收器调用<code>__del__()</code>。</p>
<p>我们也可以通过<code>del语句</code>删除对象，从而保证调用<code>__del__()</code>。</p>
<p>系统会自动提供<code>__del__</code>方法，一般不需要自定义析构方法。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 析构函数</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__del__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;销毁对象：&#123;&#125;&quot;</span>.<span class="built_in">format</span>(self))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">p1 = Person()</span><br><span class="line">p2 = Person()</span><br><span class="line"><span class="keyword">del</span> p2</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;程序结束&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">销毁对象：&lt;__main__.Person object at 0x0000021E3FE14FA0&gt;</span></span><br><span class="line"><span class="string">程序结束</span></span><br><span class="line"><span class="string">销毁对象：&lt;__main__.Person object at 0x0000021E3FE14FD0&gt;</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="call方法和可调用对象"><a href="#call方法和可调用对象" class="headerlink" title="call方法和可调用对象"></a>call方法和可调用对象</h3><p>Python中，凡是可以将<code>()</code>直接应用到自身并执行，都称为可调用对象。</p>
<p>可调用对象包括自定义的函数、Python内置函数、以及本节所讲的实例对象。</p>
<p>定义了<code>__call__()</code>的对象，称为==“可调用对象”，即该对象可以像函数一样被调用==。</p>
<p>该方法使得实例对象可以像调用普通函数那样，以<code>&quot;对象名()&quot;</code>的形式使用。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f1</span>():</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;f1&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">f1()  <span class="comment"># 本质也是调用了__call__()方法</span></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;f1&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Car</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__call__</span>(<span class="params">self, age, money</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;call方法&quot;</span>)</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;车龄&#123;0&#125;,金额&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(age, money))</span><br><span class="line">        </span><br><span class="line"></span><br><span class="line">c = Car()</span><br><span class="line">c(<span class="number">3</span>, <span class="number">20000</span>)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">call方法</span></span><br><span class="line"><span class="string">车龄3,金额20000</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="方法没有重载"><a href="#方法没有重载" class="headerlink" title="方法没有重载"></a>方法没有重载</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311191753886.png" alt="image-20231117221944194"></p>
<p>如果我们在类体中定义了多个重名的方法，只有最后一个方法有效。</p>
<p>建议：==不要使用重名的方法！Python中方法没有重载。==</p>
<blockquote>
<p>在其他一些语言（比如：Java)中，可以定义多个重名的方法，只要保证方法签名唯一即可。方法签名包含3个部分：方法名、参数数量、参数类型。<br>    Python中，方法的的参数没有声明类型（调用时确定参数的类型），参数的数量也可以由可变参数控制。因此，Python中是没有方法的重载的。</p>
</blockquote>
<h3 id="方法的动态性"><a href="#方法的动态性" class="headerlink" title="方法的动态性"></a>方法的动态性</h3><p>Python是动态语言，我们可以动态的为类添加新的方法，或者动态的修改类的已有的方法</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#测试方法的动态性</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">work</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;努力上班！&quot;</span>)</span><br><span class="line">        </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">play_game</span>(<span class="params">self</span>):</span><br><span class="line">    	<span class="built_in">print</span>(<span class="string">&quot;玩游戏&quot;</span>)</span><br><span class="line"><span class="keyword">def</span> <span class="title function_">work2</span>(<span class="params">s</span>):</span><br><span class="line">    	<span class="built_in">print</span>(<span class="string">&quot;好好工作，努力上班！&quot;</span>)</span><br><span class="line">Person.play = play_game</span><br><span class="line">Person.work = work2</span><br><span class="line">p = Person()</span><br><span class="line">p.play()</span><br><span class="line">p.work()</span><br></pre></td></tr></table></figure>
<p>我们可以看到， Person 动态的新增了 <code>play_game</code> 方法，以及用 <code>work2</code> 替换了 <code>work</code> 方法</p>
<h3 id="私有属性和私有方法-实现封装"><a href="#私有属性和私有方法-实现封装" class="headerlink" title="私有属性和私有方法(实现封装)"></a>私有属性和私有方法(实现封装)</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311191753889.png" alt="image-20231118141259542"></p>
<p>Pytho对于类的成员没有严格的访问控制限制，这与其他面向对象语言有区别。关于私有属性和私有方法，有如下要点：</p>
<p>①通常我们约定，<strong>两个下划线开头的属性是私有的(private)</strong>。其他为公 共的(public)。</p>
<p>②类内部可以访问私有属性（方法）</p>
<p>③类外部不能直接访问私有属性（方法）</p>
<p>④类外部可以通过 <code>_类名__私有属性(方法)名</code> 访问私有属性（方法）</p>
<blockquote>
<p>【注】==方法本质上也是属性！==只不过是可以通过()执行而已。</p>
<p>所以，此处讲的私有属性和公有属性，也同时讲解了私有方法和公有方法的用法。</p>
<p>如下测试中，同时也包含了私有方法和公有方法的例子。</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Employee</span>:</span><br><span class="line">    __company = <span class="string">&quot;Ailibab&quot;</span>  <span class="comment"># 私有属性，解释器运行时把__company转化成_Employee__company</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, age</span>):</span><br><span class="line">        self.name = name</span><br><span class="line">        self.__age = age   <span class="comment"># 私有属性</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_company</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;我的公司名字是：&quot;</span>, Employee.__company)</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;我的年龄是：&quot;</span>, self.__age)</span><br><span class="line">        </span><br><span class="line"> 	<span class="keyword">def</span> <span class="title function_">__work</span>(<span class="params">self</span>):  	   <span class="comment"># 私有方法</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;好好工作&quot;</span>)	</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(Employee._Employee__company)</span><br><span class="line">a = Employee(<span class="string">&quot;haha&quot;</span>, <span class="number">20</span>)</span><br><span class="line">a.say_company()</span><br><span class="line"><span class="built_in">print</span>(a._Employee__age)  <span class="comment"># 调用私有属性</span></span><br><span class="line">a._Employee__work()      <span class="comment"># 调用私有方法</span></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">Ailibab</span></span><br><span class="line"><span class="string">我的公司名字是： Ailibab</span></span><br><span class="line"><span class="string">我的年龄是： 20</span></span><br><span class="line"><span class="string">20</span></span><br><span class="line"><span class="string">好好工作</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="property装饰器"><a href="#property装饰器" class="headerlink" title="@property装饰器"></a>@property装饰器</h3><p><code>@property</code>可以将一个<strong>方法的调用方式变成“属性调用”</strong>。</p>
<p><code>@property</code>主要用于帮助我们<strong>处理属性的读操作、写操作</strong>。对于某一个属性，我们可以直接通过：</p>
<p>​                                                        <code>emp1.salary= 30000</code></p>
<p>如上的操作读操作、写操作。但是，这种做法不安全。比如，我需要限制薪水必须为<code>1-10000</code>的数字。这时候，我们就需要通过使用装饰器<code>@property</code>来处理。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Employee</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, salary</span>):</span><br><span class="line">        self.name = name</span><br><span class="line">        self.__salary = salary</span><br><span class="line"></span><br><span class="line"><span class="meta">    @property                      </span><span class="comment"># 只能读 print(emp1.salary) 相当于属性的调用</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">salary</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;薪资是：&quot;</span>, self.__salary)</span><br><span class="line">        <span class="keyword">return</span> self.__salary</span><br><span class="line"></span><br><span class="line"><span class="meta">    @salary.setter                 </span><span class="comment"># 修改使用这个函数 emp1.salary = 50000</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">salary</span>(<span class="params">self, salary</span>): </span><br><span class="line">        <span class="keyword">if</span> <span class="number">0</span> &lt; salary &lt; <span class="number">100000</span>:</span><br><span class="line">            self.__salary = salary</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="built_in">print</span>(<span class="string">&quot;薪资录入错误！只能在0-100000之间&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">emp1 = Employee(<span class="string">&quot;john&quot;</span>, <span class="number">20000</span>)</span><br><span class="line">emp1.salary = <span class="number">50000</span></span><br><span class="line"><span class="built_in">print</span>(emp1.salary)</span><br><span class="line"></span><br><span class="line">emp1.salary = <span class="number">100000000</span></span><br><span class="line"><span class="built_in">print</span>(emp1.salary)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">薪资是： 50000</span></span><br><span class="line"><span class="string">50000</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">薪资录入错误！只能在0-100000之间</span></span><br><span class="line"><span class="string">薪资是： 50000</span></span><br><span class="line"><span class="string">50000</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="属性和方法命名总结"><a href="#属性和方法命名总结" class="headerlink" title="属性和方法命名总结"></a>属性和方法命名总结</h3><p><code>_xxx</code>：保护成员，不能用<code>from module import *</code> 导入，只有类对象和子类对象能访问这些成员。</p>
<p><code>__xxx__</code>:系统定义的特殊成员</p>
<p><code>__xxx</code>:类中的私有成员，只有类对象自己能访问，子类对象也不能访问。(但，在类外部可以通过 <code>对像名._类名__xxx</code> 这种特殊方式访问。Python不存在严格意义的私有成员)</p>
<blockquote>
<p>:warning:再次强调，方法和属性都遵循上面的规则。 </p>
</blockquote>
<h3 id="类编码风格"><a href="#类编码风格" class="headerlink" title="类编码风格"></a>类编码风格</h3><ol>
<li><strong>类名首字母大写，多个单词之间采用驼峰原则。</strong></li>
<li><strong>实例名、模块名采用小写，多个单词之间采用下划线隔开</strong></li>
<li>每个类，应紧跟“文档字符串”，说明这个类的作用</li>
<li>可以用空行组织代码，但不能滥用。在类中，使用一个空行隔开方法；模块中，使用两个空行隔开多个类</li>
</ol>
<h3 id="None对象的特殊性"><a href="#None对象的特殊性" class="headerlink" title="None对象的特殊性"></a>None对象的特殊性</h3><h4 id="None是什么？"><a href="#None是什么？" class="headerlink" title="None是什么？"></a>None是什么？</h4><ol>
<li><p>与C和JAVA不同，Pythont中是没有<code>NULL</code>的，取而代之的是<code>None</code>。</p>
</li>
<li><p><code>None</code>是一个特殊的常量，表示变量没有指向任何对象。</p>
</li>
<li><p>在Python中，<code>None</code>本身实际上<strong>也是对象</strong>，有自己的类型<code>NoneType</code>。</p>
</li>
<li><p>你可以将<code>None</code>赋值给任何变量，但我们不能创建<code>NoneType</code>类型的对象</p>
</li>
</ol>
<blockquote alt= "warn"><p>None不是False，None不是0，None不是空字符串。None和任何其他的数据类型比较永远返回False。</p></blockquote>

<h4 id="None和其他类型的比较"><a href="#None和其他类型的比较" class="headerlink" title="None和其他类型的比较"></a>None和其他类型的比较</h4><p><strong>None和其他任何类型比较都会返回False</strong></p>
<p><strong>空列表、空字符串、0之间的比较</strong></p>
<ol>
<li>if语句判断时，<code>空列表[]</code>、<code>空字典&#123;&#125;</code>、<code>空元组()</code>、<code>空字符串</code>、<code>0</code>、<code>None</code>等一系列代表空和无的对象会被转换成<code>False</code></li>
<li><code>==</code>和<code>is</code>判断时，空列表、空字符串不会自动转成<code>False</code></li>
</ol>
<h3 id="面向对象的三大特征说明（封装、继承、多态）"><a href="#面向对象的三大特征说明（封装、继承、多态）" class="headerlink" title="面向对象的三大特征说明（封装、继承、多态）"></a>面向对象的三大特征说明（封装、继承、多态）</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311191753890.png" alt="image-20231118165047726"></p>
<p>==Python是面向对象的语言，支持面向对象编程的三大特性：继承、封装（隐藏）、多态。==</p>
<p><strong>封装（隐藏）</strong></p>
<blockquote>
<p>隐藏对象的属性和实现细节，只对外提供必要的方法。相当于将“细节封装起来”，只对外暴露”相关调用方法”。</p>
<p>通过前面学习的“==私有属性、私有方法”的方式，实现封装==”。Pythoni追求简洁的语法，没有严格的语法级别的“访问控制符”，更多的是依靠程序员自觉实现。</p>
</blockquote>
<p><strong>继承</strong></p>
<blockquote>
<p>继承可以让子类具有父类的特性，提高了代码的重用性。</p>
<p>从设计上是一种==增量进化==，原有父类设计不变的情况下，可以增加新的功能，或者改进已有的算法。</p>
</blockquote>
<p><strong>多态</strong></p>
<blockquote>
<p>多态是指==同一个方法调用由于对象不同会产生不同的行为==。</p>
<p>生活中这样的例子比比皆是：同样是休息方法，人不同休息方法不同。张三休息是睡觉，李四休息是玩游戏，程序员休息是“敲几行代码”。</p>
</blockquote>
<h3 id="继承详解"><a href="#继承详解" class="headerlink" title="继承详解"></a>继承详解</h3><h4 id="子类扩展父类"><a href="#子类扩展父类" class="headerlink" title="子类扩展父类"></a>子类扩展父类</h4><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051825860.png" alt="image-20240205182542943"></p>
<p>继承是面向对象编程的三大特征之一。继承让我们更加容易实现类的扩展。实现代码的重用，不用再重新发明轮子(don’t reinvent wheels)。</p>
<p>如果<strong>一个新类继承自一个设计好的类，就直接具备了已有类的特征</strong>，就大大降低了工作难度。已有的类，我们称为“父类或者基类”。新的类，我们称为“子类或者派生类”。</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311191753892.png" alt="image-20231118165736909"></p>
<h4 id="语法格式"><a href="#语法格式" class="headerlink" title="语法格式"></a>语法格式</h4><p>Python支持==多重继承，一个子类可以继承多个父类==。继承的语法格式如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">子类类名</span>(父类<span class="number">1</span>[, 父类<span class="number">2</span>, ...]):</span><br><span class="line">	类体</span><br></pre></td></tr></table></figure>
<blockquote>
<p>如果在类定义中没有指定父类，则默认父类是<code>object类</code>。也就是说，<code>object</code>是所有类的父类，里面定义了一些所有类共有的默认实现，比如：<code>__new__()</code></p>
</blockquote>
<p><strong>关于构造函数：</strong></p>
<ol>
<li><p>子类不重写<code>__init__</code>,实例化子类时，会自动调用父类定义的<code>__init__</code>。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, age</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;创建Person&quot;</span>)</span><br><span class="line">        self.name = name</span><br><span class="line">        self.age = age</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_age</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;&#123;0&#125;的年龄是&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(self.name, self.age))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span>(<span class="title class_ inherited__">Person</span>):</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">s1 = Student(<span class="string">&quot;haha&quot;</span>, <span class="number">20</span>)</span><br><span class="line">s1.say_age()</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">dir</span>(s1))</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">创建Person</span></span><br><span class="line"><span class="string">haha的年龄是20</span></span><br><span class="line"><span class="string">[&#x27;__class__&#x27;, &#x27;__delattr__&#x27;, &#x27;__dict__&#x27;, &#x27;__dir__&#x27;, &#x27;__doc__&#x27;, &#x27;__eq__&#x27;, &#x27;__format__&#x27;, &#x27;__ge__&#x27;, &#x27;__getattribute__&#x27;, &#x27;__gt__&#x27;, &#x27;__hash__&#x27;, &#x27;__init__&#x27;, &#x27;__init_subclass__&#x27;, &#x27;__le__&#x27;, &#x27;__lt__&#x27;, &#x27;__module__&#x27;, &#x27;__ne__&#x27;, &#x27;__new__&#x27;, &#x27;__reduce__&#x27;, &#x27;__reduce_ex__&#x27;, &#x27;__repr__&#x27;, &#x27;__setattr__&#x27;, &#x27;__sizeof__&#x27;, &#x27;__str__&#x27;, &#x27;__subclasshook__&#x27;, &#x27;__weakref__&#x27;, &#x27;age&#x27;, &#x27;name&#x27;, &#x27;say_age&#x27;]</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<ol>
<li><p>子类重写了<code>__init__</code>时，实例化子类，就不会调用父类已经定义的<code>__init__</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, age</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;创建Person&quot;</span>)</span><br><span class="line">        self.name = name</span><br><span class="line">        self.age = age</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_age</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;&#123;0&#125;的年龄是&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(self.name, self.age))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span>(<span class="title class_ inherited__">Person</span>):</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, age, score</span>):</span><br><span class="line">        <span class="comment"># 两种调用父类的构造方法</span></span><br><span class="line">        <span class="comment"># 1.</span></span><br><span class="line">        <span class="comment"># Person.__init__(self, name, age)</span></span><br><span class="line">        <span class="comment"># 2.</span></span><br><span class="line">        <span class="built_in">super</span>(Student, self).__init__(name, age)</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;创建Student&quot;</span>)</span><br><span class="line">        self.score = score</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_score</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;我的分数：&quot;</span>, self.score)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">s1 = Student(<span class="string">&quot;haha&quot;</span>, <span class="number">20</span>, <span class="number">90</span>)</span><br><span class="line">s1.say_score()</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">dir</span>(s1))</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">创建Person</span></span><br><span class="line"><span class="string">创建Student</span></span><br><span class="line"><span class="string">我的分数： 90</span></span><br><span class="line"><span class="string">[&#x27;__class__&#x27;, &#x27;__delattr__&#x27;, &#x27;__dict__&#x27;, &#x27;__dir__&#x27;, &#x27;__doc__&#x27;, &#x27;__eq__&#x27;, &#x27;__format__&#x27;, &#x27;__ge__&#x27;, &#x27;__getattribute__&#x27;, &#x27;__gt__&#x27;, &#x27;__hash__&#x27;, &#x27;__init__&#x27;, &#x27;__init_subclass__&#x27;, &#x27;__le__&#x27;, &#x27;__lt__&#x27;, &#x27;__module__&#x27;, &#x27;__ne__&#x27;, &#x27;__new__&#x27;, &#x27;__reduce__&#x27;, &#x27;__reduce_ex__&#x27;, &#x27;__repr__&#x27;, &#x27;__setattr__&#x27;, &#x27;__sizeof__&#x27;, &#x27;__str__&#x27;, &#x27;__subclasshook__&#x27;, &#x27;__weakref__&#x27;, &#x27;age&#x27;, &#x27;name&#x27;, &#x27;say_age&#x27;, &#x27;say_score&#x27;, &#x27;score&#x27;]</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<ol>
<li><p>如果重写了<code>__init__</code>时，要使用父类的构造方法，可以使用<code>super</code>关键字，也可以使用如下格式调用：</p>
<p>​                                                            <code>父类名.__init__(self, 参数列表)</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, age</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;创建Person&quot;</span>)</span><br><span class="line">        self.name = name</span><br><span class="line">        self.age = age</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_age</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;&#123;0&#125;的年龄是&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(self.name, self.age))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span>(<span class="title class_ inherited__">Person</span>):</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, age, score</span>):</span><br><span class="line">        <span class="comment"># 两种调用父类的构造方法</span></span><br><span class="line">        <span class="comment"># 1.</span></span><br><span class="line">        <span class="comment"># Person.__init__(self, name, age)</span></span><br><span class="line">        <span class="comment"># 2.</span></span><br><span class="line">        <span class="built_in">super</span>(Student, self).__init__(name, age)</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;创建Student&quot;</span>)</span><br><span class="line">        self.score = score</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">s1 = Student(<span class="string">&quot;haha&quot;</span>, <span class="number">20</span>, <span class="number">90</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">dir</span>(s1))</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">创建Person</span></span><br><span class="line"><span class="string">创建Student</span></span><br><span class="line"><span class="string">[&#x27;__class__&#x27;, &#x27;__delattr__&#x27;, &#x27;__dict__&#x27;, &#x27;__dir__&#x27;, &#x27;__doc__&#x27;, &#x27;__eq__&#x27;, &#x27;__format__&#x27;, &#x27;__ge__&#x27;, &#x27;__getattribute__&#x27;, &#x27;__gt__&#x27;, &#x27;__hash__&#x27;, &#x27;__init__&#x27;, &#x27;__init_subclass__&#x27;, &#x27;__le__&#x27;, &#x27;__lt__&#x27;, &#x27;__module__&#x27;, &#x27;__ne__&#x27;, &#x27;__new__&#x27;, &#x27;__reduce__&#x27;, &#x27;__reduce_ex__&#x27;, &#x27;__repr__&#x27;, &#x27;__setattr__&#x27;, &#x27;__sizeof__&#x27;, &#x27;__str__&#x27;, &#x27;__subclasshook__&#x27;, &#x27;__weakref__&#x27;, &#x27;age&#x27;, &#x27;name&#x27;, &#x27;say_age&#x27;, &#x27;score&#x27;]</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h4 id="类成员继承和重写"><a href="#类成员继承和重写" class="headerlink" title="类成员继承和重写"></a>类成员继承和重写</h4><p><strong>成员继承</strong>：==子类继承了父类除构造方法（<code>__init__()</code>）之外的所有成员。==</p>
<blockquote>
<p>:warning:私有属性、私有方法也被继承</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, age</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;创建Person&quot;</span>)</span><br><span class="line">        self.name = name</span><br><span class="line">        self.__age = age       <span class="comment"># 私有属性也会被继承</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_age</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;&#123;0&#125;的年龄是&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(self.name, self.__age))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span>(<span class="title class_ inherited__">Person</span>):</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, age, score</span>):</span><br><span class="line">        <span class="comment"># 两种调用父类的构造方法</span></span><br><span class="line">        <span class="comment"># 1.</span></span><br><span class="line">        <span class="comment"># Person.__init__(self, name, age)</span></span><br><span class="line">        <span class="comment"># 2.</span></span><br><span class="line">        <span class="built_in">super</span>(Student, self).__init__(name, age)</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;创建Student&quot;</span>)</span><br><span class="line">        self.score = score</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_score</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;我的分数：&quot;</span>, self.score)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">s1 = Student(<span class="string">&quot;haha&quot;</span>, <span class="number">20</span>, <span class="number">90</span>)</span><br><span class="line">s1.say_age()</span><br><span class="line">s1.say_score()</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">dir</span>(s1))</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">创建Person</span></span><br><span class="line"><span class="string">创建Student</span></span><br><span class="line"><span class="string">haha的年龄是20</span></span><br><span class="line"><span class="string">我的分数： 90</span></span><br><span class="line"><span class="string">[&#x27;_Person__age&#x27;, &#x27;__class__&#x27;, &#x27;__delattr__&#x27;, &#x27;__dict__&#x27;, &#x27;__dir__&#x27;, &#x27;__doc__&#x27;, &#x27;__eq__&#x27;, &#x27;__format__&#x27;, &#x27;__ge__&#x27;, &#x27;__getattribute__&#x27;, &#x27;__gt__&#x27;, &#x27;__hash__&#x27;, &#x27;__init__&#x27;, &#x27;__init_subclass__&#x27;, &#x27;__le__&#x27;, &#x27;__lt__&#x27;, &#x27;__module__&#x27;, &#x27;__ne__&#x27;, &#x27;__new__&#x27;, &#x27;__reduce__&#x27;, &#x27;__reduce_ex__&#x27;, &#x27;__repr__&#x27;, &#x27;__setattr__&#x27;, &#x27;__sizeof__&#x27;, &#x27;__str__&#x27;, &#x27;__subclasshook__&#x27;, &#x27;__weakref__&#x27;, &#x27;name&#x27;, &#x27;say_age&#x27;, &#x27;say_score&#x27;, &#x27;score&#x27;]</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p><strong>方法重写</strong>：子类可以重新定义父类中的方法，这样就会覆盖父类的方法，也称为“重写”</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, age</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;创建Person&quot;</span>)</span><br><span class="line">        self.name = name</span><br><span class="line">        self.age = age</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_age</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;&#123;0&#125;的年龄是&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(self.name, self.age))</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_name</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;我的名字是：&quot;</span>, self.name)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span>(<span class="title class_ inherited__">Person</span>):</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, age, score</span>):</span><br><span class="line">        Person.__init__(self, name, age)</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;创建Student&quot;</span>)</span><br><span class="line">        self.score = score</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_score</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;我的分数：&quot;</span>, self.score)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_name</span>(<span class="params">self</span>):    <span class="comment"># 重写父类的方法</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;hello ,my name is &quot;</span>, self.name)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">s1 = Student(<span class="string">&quot;haha&quot;</span>, <span class="number">20</span>, <span class="number">90</span>)</span><br><span class="line">s1.say_age()</span><br><span class="line">s1.say_score()</span><br><span class="line">s1.say_name()</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">dir</span>(s1))</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">创建Person</span></span><br><span class="line"><span class="string">创建Student</span></span><br><span class="line"><span class="string">haha的年龄是20</span></span><br><span class="line"><span class="string">我的分数： 90</span></span><br><span class="line"><span class="string">hello ,my name is  haha</span></span><br><span class="line"><span class="string">[&#x27;__class__&#x27;, &#x27;__delattr__&#x27;, &#x27;__dict__&#x27;, &#x27;__dir__&#x27;, &#x27;__doc__&#x27;, &#x27;__eq__&#x27;, &#x27;__format__&#x27;, &#x27;__ge__&#x27;, &#x27;__getattribute__&#x27;, &#x27;__gt__&#x27;, &#x27;__hash__&#x27;, &#x27;__init__&#x27;, &#x27;__init_subclass__&#x27;, &#x27;__le__&#x27;, &#x27;__lt__&#x27;, &#x27;__module__&#x27;, &#x27;__ne__&#x27;, &#x27;__new__&#x27;, &#x27;__reduce__&#x27;, &#x27;__reduce_ex__&#x27;, &#x27;__repr__&#x27;, &#x27;__setattr__&#x27;, &#x27;__sizeof__&#x27;, &#x27;__str__&#x27;, &#x27;__subclasshook__&#x27;, &#x27;__weakref__&#x27;, &#x27;age&#x27;, &#x27;name&#x27;, &#x27;say_age&#x27;, &#x27;say_name&#x27;, &#x27;say_score&#x27;, &#x27;score&#x27;]</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h4 id="查看类的继承层次结构"><a href="#查看类的继承层次结构" class="headerlink" title="查看类的继承层次结构"></a>查看类的继承层次结构</h4><p>通过类的方法<code>mro()</code>或者类的属性<code>__mro__</code>可以输出这个类的继承层次结构。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">A</span>:</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">B</span>(<span class="title class_ inherited__">A</span>):</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">C</span>(<span class="title class_ inherited__">B</span>):</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(C.mro())</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">[&lt;class &#x27;__main__.C&#x27;&gt;, &lt;class &#x27;__main__.B&#x27;&gt;, &lt;class &#x27;__main__.A&#x27;&gt;, &lt;class &#x27;object&#x27;&gt;]</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311191753893.png" alt="image-20231118173835027"></p>
<h3 id="object根类"><a href="#object根类" class="headerlink" title="object根类"></a>object根类</h3><blockquote>
<p>==<code>object</code>类是所有类的父类==，因此所有的类都有<code>object</code>类的属性和方法。我们显然有必要深入研究一下<code>object</code>类的结构。对于我们继续深入学习Python很有好处。</p>
</blockquote>
<h4 id="dir-查看对象属性"><a href="#dir-查看对象属性" class="headerlink" title="dir()查看对象属性"></a><code>dir()</code>查看对象属性</h4><p>为了深入学习对象，先学习内置函数<code>dir()</code>,他可以让我们方便的看到指定对象所有的属性</p>
<blockquote>
<p>:warning:快捷键 Alt+ 7 打开模块结构</p>
</blockquote>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311191753895.png" alt="image-20231118175130469"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, age</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;创建Person&quot;</span>)</span><br><span class="line">        self.name = name</span><br><span class="line">        self.age = age</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_age</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;&#123;0&#125;的年龄是&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(self.name, self.age))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 快捷键 Alt+ 7 打开模块结构</span></span><br><span class="line">obj = <span class="built_in">object</span>()</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">dir</span>(obj))</span><br><span class="line"></span><br><span class="line">s2 = Person(<span class="string">&quot;haha&quot;</span>, <span class="number">20</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">dir</span>(s2))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 方法的本质也是是属性</span></span><br><span class="line"><span class="built_in">print</span>(s2.say_age)</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(s2.say_age))</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">[&#x27;__class__&#x27;, &#x27;__delattr__&#x27;, &#x27;__dir__&#x27;, &#x27;__doc__&#x27;, &#x27;__eq__&#x27;, &#x27;__format__&#x27;, &#x27;__ge__&#x27;, &#x27;__getattribute__&#x27;, &#x27;__gt__&#x27;, &#x27;__hash__&#x27;, &#x27;__init__&#x27;, &#x27;__init_subclass__&#x27;, &#x27;__le__&#x27;, &#x27;__lt__&#x27;, &#x27;__ne__&#x27;, &#x27;__new__&#x27;, &#x27;__reduce__&#x27;, &#x27;__reduce_ex__&#x27;, &#x27;__repr__&#x27;, &#x27;__setattr__&#x27;, &#x27;__sizeof__&#x27;, &#x27;__str__&#x27;, &#x27;__subclasshook__&#x27;]</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">创建Person</span></span><br><span class="line"><span class="string">[&#x27;__class__&#x27;, &#x27;__delattr__&#x27;, &#x27;__dict__&#x27;, &#x27;__dir__&#x27;, &#x27;__doc__&#x27;, &#x27;__eq__&#x27;, &#x27;__format__&#x27;, &#x27;__ge__&#x27;, &#x27;__getattribute__&#x27;, &#x27;__gt__&#x27;, &#x27;__hash__&#x27;, &#x27;__init__&#x27;, &#x27;__init_subclass__&#x27;, &#x27;__le__&#x27;, &#x27;__lt__&#x27;, &#x27;__module__&#x27;, &#x27;__ne__&#x27;, &#x27;__new__&#x27;, &#x27;__reduce__&#x27;, &#x27;__reduce_ex__&#x27;, &#x27;__repr__&#x27;, &#x27;__setattr__&#x27;, &#x27;__sizeof__&#x27;, &#x27;__str__&#x27;, &#x27;__subclasshook__&#x27;, &#x27;__weakref__&#x27;, &#x27;age&#x27;, &#x27;name&#x27;, &#x27;say_age&#x27;]</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&lt;bound method Person.say_age of &lt;__main__.Person object at 0x00000222E819BFD0&gt;&gt;</span></span><br><span class="line"><span class="string">&lt;class &#x27;method&#x27;&gt;</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<p><strong>从上面我们可以发现这样几个要点：</strong></p>
<ol>
<li>Person对象增加了六个属性：<code>__dict__</code> <code>__module__</code> <code>__weakref__</code> <code>age</code> <code>name</code> <code>say_age</code></li>
<li><code>object</code>的所有属性，<code>Person</code>类作为<code>object</code>的子类，显然包含了所有的属性</li>
<li>我们打印<code>age</code>、<code>name</code>、<code>say_age</code>，发现<code>say_age</code>虽然是==方法，实际上也是属性==。只不过这个属性的类型是method而已。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">age &lt;<span class="keyword">class</span> <span class="string">&#x27;int&#x27;</span>&gt;</span><br><span class="line">name &lt;<span class="keyword">class</span> <span class="string">&#x27;str&#x27;</span>&gt;</span><br><span class="line">say_age &lt;<span class="keyword">class</span> <span class="string">&#x27;method&#x27;</span>&gt;</span><br></pre></td></tr></table></figure>
<h4 id="重写-str-方法"><a href="#重写-str-方法" class="headerlink" title="重写__str__()方法"></a>重写<code>__str__()</code>方法</h4><ol>
<li><code>object</code>有一个<code>__str()__</code>方法，用于返回一个对于”对象的描述”。内置函数<code>str(对象)</code>，调用的就是<code>__str()__</code></li>
<li><code>__str()__</code>经常用于<code>print()</code>方法，帮助我们查看对象的信息。<code>__str()__</code>可以重写</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, age</span>):</span><br><span class="line">        self.name = name</span><br><span class="line">        self.age = age</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__str__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="string">&quot;&quot;&quot;将对象转化成一个字符串描述，一般用于print方法&quot;&quot;&quot;</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;重写str方法&quot;</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;名字是：&#123;0&#125;，年龄是&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(self.name, self.age)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">p = Person(<span class="string">&quot;haha&quot;</span>, <span class="number">20</span>)</span><br><span class="line"><span class="built_in">print</span>(p)</span><br><span class="line">s = <span class="built_in">str</span>(p)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">重写str方法</span></span><br><span class="line"><span class="string">名字是：haha，年龄是20</span></span><br><span class="line"><span class="string">重写str方法</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="多重继承"><a href="#多重继承" class="headerlink" title="多重继承"></a>多重继承</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311191753896.png" alt="image-20231118181906059"></p>
<blockquote>
<p>Pytho支持多重继承，一个子类可以有多个”直接父类”。这样，就具备了”多个父类”的特点。但是由于，这样会被“类的整体层次””搞的异常复杂，==尽量避免使用==。</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">A</span>:</span><br><span class="line">   	<span class="keyword">def</span> <span class="title function_">aa</span>(<span class="params">self</span>):</span><br><span class="line">       	<span class="built_in">print</span>(<span class="string">&quot;aa&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">B</span>:</span><br><span class="line">  	<span class="keyword">def</span> <span class="title function_">bb</span>(<span class="params">self</span>):</span><br><span class="line">       	<span class="built_in">print</span>(<span class="string">&quot;bb&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">C</span>(B,A):</span><br><span class="line">   	<span class="keyword">def</span> <span class="title function_">cc</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;cc&quot;</span>)</span><br><span class="line"></span><br><span class="line">c = C()</span><br><span class="line">c.cc()</span><br><span class="line">c.bb()</span><br><span class="line">c.aa()</span><br></pre></td></tr></table></figure>
<p>类结构为：</p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202402051831894.png" alt="image-20240205183106268"></p>
<h3 id="MRO方法解析顺序"><a href="#MRO方法解析顺序" class="headerlink" title="MRO方法解析顺序"></a>MRO方法解析顺序</h3><p>Pythor支持多继承，如果父类中有相同名字的方法，在子类没有指定父类名时，解释器将<strong>“从左向右”</strong>按顺序搜索。</p>
<p>MRO(Method Resolution Order):方法解析顺序。我们可以通过<code>mro()</code>方法获得”类的层次结构”，方法解析顺序也是按照这个“类的层次结构”寻找的。</p>
<h3 id="super-获得父类的定义"><a href="#super-获得父类的定义" class="headerlink" title="super()获得父类的定义"></a>super()获得父类的定义</h3><p>在子类中，如果想要获得父类的方法时，我们可以通过<code>super()</code>来做。</p>
<p><code>super()</code>代表<strong>父类的定义，不是父类对象</strong>。</p>
<blockquote>
<p>想调用父类的构造方法：</p>
<p><code>super(子类名称, self).__init__(参数列表)</code></p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span>:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, age</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;创建Person&quot;</span>)</span><br><span class="line">        self.name = name</span><br><span class="line">        self.__age = age       <span class="comment"># 私有属性也会被继承</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_age</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;&#123;0&#125;的年龄是&#123;1&#125;&quot;</span>.<span class="built_in">format</span>(self.name, self.__age))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span>(<span class="title class_ inherited__">Person</span>):</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name, age, score</span>):</span><br><span class="line">        <span class="comment"># Person.__init__(self)</span></span><br><span class="line">        <span class="built_in">super</span>(Student, self).__init__(name, age)  <span class="comment"># 调用父类的构造方法</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;创建Student&quot;</span>)</span><br><span class="line">        self.score = score</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">say_age</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="comment"># Person.say_age(self)</span></span><br><span class="line">        <span class="built_in">super</span>().say_age()					<span class="comment"># 通过super()调用父类的方法</span></span><br><span class="line">        </span><br><span class="line">        </span><br></pre></td></tr></table></figure>
<h3 id="多态详解"><a href="#多态详解" class="headerlink" title="多态详解"></a>多态详解</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311191753897.png" alt="image-20231119160951739"></p>
<p><strong>多态(polymorphism)是指同一个方法调用由于对象不同可能会产生不同的行为。</strong></p>
<p>关于多态要注意以下2点：</p>
<ol>
<li><strong>多态是方法的多态，属性没有多态</strong>。</li>
<li>多态的存在有==2个必要条件：继承、方法重写==</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Animal</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">shout</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;动物叫了一声&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Dog</span>(<span class="title class_ inherited__">Animal</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">shout</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;小狗叫了一声&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Cat</span>(<span class="title class_ inherited__">Animal</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">shout</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;小猫叫了一声&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">animalShout</span>(<span class="params">a</span>):</span><br><span class="line">    a.shout()  <span class="comment"># 会产生多态，传入对象不同，则调用方法不同</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">animalShout(Dog())</span><br><span class="line">animalShout(Cat())</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">小狗叫了一声</span></span><br><span class="line"><span class="string">小猫叫了一声</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h3 id="特殊方法和运算符重载"><a href="#特殊方法和运算符重载" class="headerlink" title="特殊方法和运算符重载"></a>特殊方法和运算符重载</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311191753898.png" alt="image-20231119162419296"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311191753899.png" alt="image-20231119162554609"></p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311191753900.png" alt="image-20231119162639978"></p>
<h3 id="特殊属性"><a href="#特殊属性" class="headerlink" title="特殊属性"></a>特殊属性</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311191753901.png" alt="image-20231119162849422"></p>
<h3 id="对象的浅拷贝和深拷贝"><a href="#对象的浅拷贝和深拷贝" class="headerlink" title="对象的浅拷贝和深拷贝"></a>对象的浅拷贝和深拷贝</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311191753902.png" alt="image-20231119163101534"></p>
<h4 id="浅拷贝"><a href="#浅拷贝" class="headerlink" title="浅拷贝"></a>浅拷贝</h4><p>Python拷贝一般都是浅拷贝。</p>
<p>浅拷贝：拷贝时，拷贝源对象，但对象包含的子对象内容不拷贝。</p>
<h4 id="深拷贝"><a href="#深拷贝" class="headerlink" title="深拷贝"></a>深拷贝</h4><p>使用 <code>copy</code> 模块的 <code>deepcopy</code> 函数，递归拷贝对象中包含的子对象。</p>
<p>深拷贝：拷贝时，拷贝源对象，也递归拷贝对象中包含的子对象</p>
<h3 id="组合"><a href="#组合" class="headerlink" title="组合"></a>组合</h3><p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311191753903.png" alt="image-20231119164344071"></p>
<p>除了继承，“组合”也能实现代码的复用！“<strong>组合”核心是“将父类对象作为子类的属性”</strong>。</p>
<blockquote>
<p><code>is-a</code>关系，我们可以使用”<strong>==继承==</strong>”。从而实现子类拥有的父类的方法和属性。<code>is-a</code>关系指的是类似这样的关系：狗是动物，dog is animal。狗类就应该继承动物类。</p>
<p><code>has-a</code>关系，我们可以使用”==组合==”，也能实现一个类拥有另一个类的方法和属性。<code>has-a</code>关系指的是这样的关系：手机拥有CPU。MobilePhone has a CPU</p>
</blockquote>
<h3 id="设计模式"><a href="#设计模式" class="headerlink" title="设计模式"></a>设计模式</h3><p>设计模式是面向对象语言特有的内容，是我们在面临某一类问题时候固定的做法，设计模式有很多种，比较流行的是：GOF(Goup Of Four)23种设计模式。当然，我们没有必要全部学习，学习几个常用的即可。</p>
<p>对于初学者，我们学习两个最常用的模式：工厂模式和单例模式。</p>
<h4 id="工厂模式实现"><a href="#工厂模式实现" class="headerlink" title="工厂模式实现"></a>工厂模式实现</h4><p>工厂模式实现了<strong>创建者和调用者的分离</strong>，使用专门的工厂类将选择实现类、创建对象进行统一的管理和控制。 </p>
<p><img src="https://gitee.com/huaiyuechusan/picture/raw/master/Typora/202311191753904.png" alt="image-20231119165631900"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 工厂模式实现</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Benz</span>: <span class="keyword">pass</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">BMW</span>: <span class="keyword">pass</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">BYD</span>: <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">CarFactory</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createCar</span>(<span class="params">self, brand</span>):</span><br><span class="line">        <span class="keyword">if</span> brand == <span class="string">&quot;宝马&quot;</span>:</span><br><span class="line">            <span class="keyword">return</span> BMW()</span><br><span class="line">        <span class="keyword">elif</span> brand == <span class="string">&quot;奔驰&quot;</span>:</span><br><span class="line">            <span class="keyword">return</span> Benz()</span><br><span class="line">        <span class="keyword">elif</span> brand == <span class="string">&quot;比亚迪&quot;</span>:</span><br><span class="line">            <span class="keyword">return</span> BYD()</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;未知品牌，无法创建&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">factory = CarFactory()</span><br><span class="line">c1 = factory.createCar(<span class="string">&quot;奔驰&quot;</span>)</span><br><span class="line">c2 = factory.createCar(<span class="string">&quot;宝马&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(c1)</span><br><span class="line"><span class="built_in">print</span>(c2)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">&lt;__main__.Benz object at 0x0000021C16D12FA0&gt;</span></span><br><span class="line"><span class="string">&lt;__main__.BMW object at 0x0000021C16D12F70&gt;</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h4 id="单例模式实现"><a href="#单例模式实现" class="headerlink" title="单例模式实现"></a>单例模式实现</h4><p>单例模式(Singleton Pattern)的核心作用是确保<strong>一个类只有一个实例</strong>，并且提供<strong>一个访问该实例的全局访问点</strong>。</p>
<p>单例模式只生成一个实例对象，减少了对系统资源的开销。当一个对象的产生需要比较多的资源，如读取配置文件、产生其他依赖对象时，可以产生一个“单例对象”，然后永久驻留内存中，从而极大的降低开销。</p>
<blockquote alt="warn"><p>单例模式有多种实现的方式，我们这里推荐重写__new__()的方法。</p></blockquote>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 单例模式实现</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MySingleton</span>:</span><br><span class="line">    __obj = <span class="literal">None</span></span><br><span class="line">    __init_flag = <span class="literal">True</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__new__</span>(<span class="params">cls, *args, **kwargs</span>):</span><br><span class="line">        <span class="keyword">if</span> cls.__obj <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">            cls.__obj = <span class="built_in">object</span>.__new__(cls)</span><br><span class="line">        <span class="keyword">return</span> cls.__obj</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, name</span>):</span><br><span class="line">        <span class="keyword">if</span> MySingleton.__init_flag:</span><br><span class="line">            <span class="built_in">print</span>(<span class="string">&quot;初始化第一个对象...&quot;</span>)</span><br><span class="line">            self.name = name</span><br><span class="line">            MySingleton.__init_flag = <span class="literal">False</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">a = MySingleton(<span class="string">&quot;aa&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(a)</span><br><span class="line">b = MySingleton(<span class="string">&quot;bb&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(b)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">初始化第一个对象...</span></span><br><span class="line"><span class="string">&lt;__main__.MySingleton object at 0x000001E70B8E2FA0&gt;</span></span><br><span class="line"><span class="string">&lt;__main__.MySingleton object at 0x000001E70B8E2FA0&gt;</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h4 id="工厂和单例模式结合起来"><a href="#工厂和单例模式结合起来" class="headerlink" title="工厂和单例模式结合起来"></a>工厂和单例模式结合起来</h4><p>设计模式称之为“模式”，就是一些固定的套路。我们很容易用到其他场景上，比如前面讲的工厂模式，我们需要将工厂类定义成“单例”，只需要简单的套用即可实现：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 工厂和单例模式结合</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">CarFactory</span>:</span><br><span class="line">    __obj = <span class="literal">None</span></span><br><span class="line">    __init_flag = <span class="literal">True</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__new__</span>(<span class="params">cls, *args, **kwargs</span>):</span><br><span class="line">        <span class="keyword">if</span> cls.__obj <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">            cls.__obj = <span class="built_in">object</span>.__new__(cls)</span><br><span class="line">        <span class="keyword">return</span> cls.__obj</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">if</span> CarFactory.__init_flag:</span><br><span class="line">            <span class="built_in">print</span>(<span class="string">&quot;初始化第一个对象...&quot;</span>)</span><br><span class="line">            CarFactory.__init_flag = <span class="literal">False</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">createCar</span>(<span class="params">self, brand</span>):</span><br><span class="line">        <span class="keyword">if</span> brand == <span class="string">&quot;宝马&quot;</span>:</span><br><span class="line">            <span class="keyword">return</span> BMW()</span><br><span class="line">        <span class="keyword">elif</span> brand == <span class="string">&quot;奔驰&quot;</span>:</span><br><span class="line">            <span class="keyword">return</span> Benz()</span><br><span class="line">        <span class="keyword">elif</span> brand == <span class="string">&quot;比亚迪&quot;</span>:</span><br><span class="line">            <span class="keyword">return</span> BYD()</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;未知品牌，无法创建&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Benz</span>: </span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">BMW</span>: </span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">BYD</span>: </span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">factory = CarFactory()</span><br><span class="line">c1 = factory.createCar(<span class="string">&quot;奔驰&quot;</span>)</span><br><span class="line">c2 = factory.createCar(<span class="string">&quot;宝马&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(c1)</span><br><span class="line"><span class="built_in">print</span>(c2)</span><br><span class="line">factory2 = CarFactory()</span><br><span class="line"><span class="built_in">print</span>(factory)</span><br><span class="line"><span class="built_in">print</span>(factory2)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">初始化第一个对象...</span></span><br><span class="line"><span class="string">&lt;__main__.Benz object at 0x0000018C683F3F70&gt;</span></span><br><span class="line"><span class="string">&lt;__main__.BMW object at 0x0000018C683F3F10&gt;</span></span><br><span class="line"><span class="string">&lt;__main__.CarFactory object at 0x0000018C683F3FA0&gt;</span></span><br><span class="line"><span class="string">&lt;__main__.CarFactory object at 0x0000018C683F3FA0&gt;</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>
<h2 id="Python开发环境搭建"><a href="#Python开发环境搭建" class="headerlink" title="Python开发环境搭建"></a>Python开发环境搭建</h2><p>环境配置参考这篇文章</p>
<p><a target="_blank" rel="noopener external nofollow noreferrer" href="https://mp.weixin.qq.com/s/L2odIhRhxVE9CZefJDGRvQ">Python环境配置保姆教程（Anaconda、Jupyter、GPU环境）！</a></p>
<p>内容包括:</p>
<ul>
<li>Anaconda的安装与常用命令小总</li>
<li>Jupyter的安装与相关配置</li>
<li>CUDA与Cudnn的安装(GPU支持必备)</li>
<li>建立tf虚拟环境并安装tf2.0GPU版本</li>
<li>建立pytorch虚拟环境并安装pytorchGPU版本</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://huaiyuechusan.github.io">SanShui</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://huaiyuechusan.github.io/archives/d9ef328.html">https://huaiyuechusan.github.io/archives/d9ef328.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow noreferrer" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://huaiyuechusan.github.io" target="_blank">SanShui的个人博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E5%AD%A6%E4%B9%A0%E6%8A%80%E6%9C%AF/">学习技术</a><a class="post-meta__tags" href="/tags/Python/">Python</a></div><div class="post_share"><div class="social-share" data-image="http://wallpaper.csun.site/?4" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/img/wechat.jpg" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src="/img/alipay.jpg" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/archives/59cb3162.html"><img class="prev-cover" src="http://wallpaper.csun.site/?11" onerror="onerror=null;src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">大数据集群软件启动脚本</div></div></a></div><div class="next-post pull-right"><a href="/archives/7cb9f0a8.html"><img class="next-cover" src="http://wallpaper.csun.site/?23" onerror="onerror=null;src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">通过nginx访问tomcat中SpringMVC应用</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/archives/984515cf.html" title="Python 网络与并发编程"><img class="cover" src="http://wallpaper.csun.site/?6" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-10-17</div><div class="title">Python 网络与并发编程</div></div></a></div><div><a href="/archives/fab44cdf.html" title="函数式编程和Python新核心特性"><img class="cover" src="http://wallpaper.csun.site/?7" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-10-17</div><div class="title">函数式编程和Python新核心特性</div></div></a></div><div><a href="/archives/8df5f8b9.html" title="Python深入和提高"><img class="cover" src="http://wallpaper.csun.site/?5" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-10-17</div><div class="title">Python深入和提高</div></div></a></div><div><a href="/archives/6d169344.html" title="云函数调用request请求"><img class="cover" src="http://wallpaper.csun.site/?21" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-10-17</div><div class="title">云函数调用request请求</div></div></a></div><div><a href="/archives/d4b1abad.html" title="下载M3U8格式加密视频"><img class="cover" src="http://wallpaper.csun.site/?22" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-10-17</div><div class="title">下载M3U8格式加密视频</div></div></a></div><div><a href="/archives/59cb3162.html" title="大数据集群软件启动脚本"><img class="cover" src="http://wallpaper.csun.site/?11" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-10-17</div><div class="title">大数据集群软件启动脚本</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="lv-container" data-id="city" data-uid="MTAyMC81OTEzMS8zNTU5Mw=="></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/./img/config_img/%E9%98%B3%E5%85%89%E5%B0%8F%E7%8C%AB.jpg" onerror="this.onerror=null;this.src='/./img/config_img/%E8%93%9D%E5%A4%A9.jpg'" alt="avatar"/></div><div class="author-info__name">SanShui</div><div class="author-info__description">今天不学习，明天变垃圾</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">25</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">16</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div><a id="card-info-btn" target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/huaiyuechusan"><i class="fa-sharp fa-solid fa-plane"></i><span>欢迎关注我的Github</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/huaiyuechusan" rel="external nofollow noreferrer" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://huaiyuechusan.github.io/atom.xml" target="_blank" title=""><i class="fas fa-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">欢迎来到SanShui的博客</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Python%E5%85%A5%E9%97%A8"><span class="toc-text">Python入门</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BC%96%E7%A8%8B%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5"><span class="toc-text">编程基本概念</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Python%E7%A8%8B%E5%BA%8F%E7%9A%84%E6%9E%84%E6%88%90"><span class="toc-text">Python程序的构成</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E7%9A%84%E7%BB%84%E7%BB%87%E5%92%8C%E7%BC%A9%E8%BF%9B"><span class="toc-text">代码的组织和缩进</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-%E8%A1%8C%E8%BF%9E%E6%8E%A5%E7%AC%A6"><span class="toc-text">使用\行连接符</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1"><span class="toc-text">对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%95%E7%94%A8"><span class="toc-text">引用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A0%87%E8%AF%86%E7%AC%A6%E8%A7%84%E5%88%99"><span class="toc-text">标识符规则</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E7%94%A8%E6%B3%95"><span class="toc-text">基本用法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Python%E6%A0%87%E8%AF%86%E7%AC%A6%E5%91%BD%E5%90%8D%E8%A7%84%E5%88%99"><span class="toc-text">Python标识符命名规则</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%98%E9%87%8F%E5%92%8C%E7%AE%80%E5%8D%95%E8%B5%8B%E5%80%BC%E8%AF%AD%E5%8F%A5"><span class="toc-text">变量和简单赋值语句</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8F%98%E9%87%8F%E7%9A%84%E5%A3%B0%E6%98%8E%E5%92%8C%E8%B5%8B%E5%80%BC"><span class="toc-text">变量的声明和赋值</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%A0%E9%99%A4%E5%8F%98%E9%87%8F%E5%92%8C%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E6%9C%BA%E5%88%B6"><span class="toc-text">删除变量和垃圾回收机制</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B8%B8%E9%87%8F"><span class="toc-text">常量</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%93%BE%E5%BC%8F%E8%B5%8B%E5%80%BC"><span class="toc-text">链式赋值</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%B3%BB%E5%88%97%E8%A7%A3%E5%8C%85%E8%B5%8B%E5%80%BC"><span class="toc-text">系列解包赋值</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9C%80%E5%9F%BA%E6%9C%AC%E5%86%85%E7%BD%AE%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B"><span class="toc-text">最基本内置数据类型</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%95%B0%E5%AD%97%E5%92%8C%E5%9F%BA%E6%9C%AC%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-text">数字和基本运算符</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%95%B4%E6%95%B0"><span class="toc-text">整数</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%B8%89%E7%A7%8D%E8%BF%9B%E5%88%B6"><span class="toc-text">三种进制</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8int-%E5%AE%9E%E7%8E%B0%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2"><span class="toc-text">使用int()实现类型转换</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%87%AA%E5%8A%A8%E8%BD%AC%E5%9E%8B"><span class="toc-text">自动转型</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%95%B4%E6%95%B0%E5%8F%AF%E4%BB%A5%E4%BB%BB%E6%84%8F%E5%A4%A7"><span class="toc-text">整数可以任意大</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B5%AE%E7%82%B9%E6%95%B0-float"><span class="toc-text">浮点数 float</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2%E5%92%8C%E5%9B%9B%E8%88%8D%E4%BA%94%E5%85%A5"><span class="toc-text">类型转换和四舍五入</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%A2%9E%E5%BC%BA%E5%9E%8B%E8%B5%8B%E5%80%BC%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-text">增强型赋值运算符</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%97%B6%E9%97%B4%E7%9A%84%E8%A1%A8%E7%A4%BA"><span class="toc-text">时间的表示</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B8%83%E5%B0%94%E5%80%BC"><span class="toc-text">布尔值</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-text">运算符</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%80%BB%E8%BE%91%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-text">逻辑运算符</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%AF%94%E8%BE%83%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-text">比较运算符</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%8D%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-text">位运算符</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8A%A0%E6%B3%95%E6%93%8D%E4%BD%9C%E8%A1%A5%E5%85%85"><span class="toc-text">加法操作补充</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B9%98%E6%B3%95%E6%93%8D%E4%BD%9C%E8%A1%A5%E5%85%85"><span class="toc-text">乘法操作补充</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%A2%9E%E5%BC%BA%E8%B5%8B%E5%80%BC%E8%BF%90%E7%AE%97%E7%AC%A6-%E8%A1%A5%E5%85%85"><span class="toc-text">增强赋值运算符(补充)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%90%8C%E4%B8%80%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-text">同一运算符</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%95%B4%E6%95%B0%E7%BC%93%E5%AD%98%E9%97%AE%E9%A2%98"><span class="toc-text">整数缓存问题</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%88%90%E5%91%98%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-text">成员运算符</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%BF%90%E7%AE%97%E7%AC%A6%E4%BC%98%E5%85%88%E7%BA%A7%E9%97%AE%E9%A2%98"><span class="toc-text">运算符优先级问题</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E8%BF%90%E7%AE%97%E7%AC%A6%E6%80%BB%E7%BB%93"><span class="toc-text">基本运算符总结</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BA%8F%E5%88%97"><span class="toc-text">序列</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BA%8F%E5%88%97%E7%9A%84%E6%9C%AC%E8%B4%A8%E5%92%8C%E5%86%85%E5%AD%98%E7%BB%93%E6%9E%84"><span class="toc-text">序列的本质和内存结构</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-text">字符串</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%9F%BA%E6%9C%AC%E7%89%B9%E7%82%B9"><span class="toc-text">字符串基本特点</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84%E7%BC%96%E7%A0%81"><span class="toc-text">字符串的编码</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%BC%95%E5%8F%B7%E5%88%9B%E5%BB%BA%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-text">引号创建字符串</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%A9%BA%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%92%8Clen-%E5%87%BD%E6%95%B0"><span class="toc-text">空字符串和len()函数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%BD%AC%E4%B9%89%E5%AD%97%E7%AC%A6"><span class="toc-text">转义字符</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%8B%BC%E6%8E%A5"><span class="toc-text">字符串拼接</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%A4%8D%E5%88%B6"><span class="toc-text">字符串复制</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%8D%E6%8D%A2%E8%A1%8C%E6%89%93%E5%8D%B0"><span class="toc-text">不换行打印</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BB%8E%E6%8E%A7%E5%88%B6%E5%8F%B0%E8%AF%BB%E5%8F%96%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-text">从控制台读取字符串</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#replace-%E5%AE%9E%E7%8E%B0%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%9B%BF%E6%8D%A2"><span class="toc-text">replace()实现字符串替换</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#str-%E5%AE%9E%E7%8E%B0%E6%95%B0%E5%AD%97%E8%BD%AC%E5%9E%8B%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-text">str()实现数字转型字符串</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-%E6%8F%90%E5%8F%96%E5%AD%97%E7%AC%A6"><span class="toc-text">使用[]提取字符</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%88%87%E7%89%87slice%E6%93%8D%E4%BD%9C"><span class="toc-text">字符串切片slice操作</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#split-%E5%88%86%E5%89%B2%E5%92%8Cjoin-%E5%90%88%E5%B9%B6"><span class="toc-text">split()分割和join()合并</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E9%A9%BB%E7%95%99%E6%9C%BA%E5%88%B6"><span class="toc-text">字符串驻留机制</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%AF%94%E8%BE%83%E5%92%8C%E5%90%8C%E4%B8%80%E6%80%A7"><span class="toc-text">字符串比较和同一性</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%88%90%E5%91%98%E6%93%8D%E4%BD%9C%E7%AC%A6%E5%88%A4%E6%96%AD%E5%AD%90%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-text">成员操作符判断子字符串</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95%E6%B1%87%E6%80%BB"><span class="toc-text">字符串常用方法汇总</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%B8%B8%E7%94%A8%E6%9F%A5%E6%89%BE%E6%96%B9%E6%B3%95"><span class="toc-text">常用查找方法</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%8E%BB%E9%99%A4%E9%A6%96%E5%B0%BE%E4%BF%A1%E6%81%AF"><span class="toc-text">去除首尾信息</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%A4%A7%E5%B0%8F%E5%86%99%E8%BD%AC%E6%8D%A2"><span class="toc-text">大小写转换</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%A0%BC%E5%BC%8F%E6%8E%92%E7%89%88"><span class="toc-text">格式排版</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E7%89%B9%E5%BE%81%E5%88%A4%E6%96%AD%E6%96%B9%E6%B3%95"><span class="toc-text">特征判断方法</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84%E6%A0%BC%E5%BC%8F%E5%8C%96"><span class="toc-text">字符串的格式化</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#format-%E5%9F%BA%E6%9C%AC%E7%94%A8%E6%B3%95"><span class="toc-text">format() 基本用法</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%A1%AB%E5%85%85%E4%B8%8E%E5%AF%B9%E9%BD%90"><span class="toc-text">填充与对齐</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%95%B0%E5%AD%97%E6%A0%BC%E5%BC%8F%E5%8C%96"><span class="toc-text">数字格式化</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8F%AF%E5%8F%98%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-text">可变字符串</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2%E6%80%BB%E7%BB%93"><span class="toc-text">类型转换总结</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%97%E8%A1%A8"><span class="toc-text">列表</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%97%E8%A1%A8%E7%AE%80%E4%BB%8B"><span class="toc-text">列表简介</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%97%E8%A1%A8%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95"><span class="toc-text">列表对象的常用方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E5%88%97%E8%A1%A8%E7%9A%844%E7%A7%8D%E6%96%B9%E5%BC%8F"><span class="toc-text">创建列表的4种方式</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E8%AF%AD%E6%B3%95-%E5%88%9B%E5%BB%BA"><span class="toc-text">基本语法 []创建</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#list-%E5%88%9B%E5%BB%BA"><span class="toc-text">list()创建</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#range-%E5%88%9B%E5%BB%BA%E6%95%B4%E6%95%B0%E5%88%97%E8%A1%A8"><span class="toc-text">range()创建整数列表</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%8E%A8%E5%AF%BC%E5%BC%8F%E7%94%9F%E6%88%90%E5%88%97%E8%A1%A8"><span class="toc-text">推导式生成列表</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%A2%9E%E5%8A%A0%E5%88%97%E8%A1%A8%E5%85%83%E7%B4%A0%E7%9A%845%E7%A7%8D%E6%96%B9%E5%BC%8F"><span class="toc-text">增加列表元素的5种方式</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#append-%E6%96%B9%E6%B3%95"><span class="toc-text">append()方法</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%BF%90%E7%AE%97%E7%AC%A6%E6%93%8D%E4%BD%9C"><span class="toc-text">+运算符操作</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#extend-%E6%96%B9%E6%B3%95"><span class="toc-text">extend()方法</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#insert-%E6%8F%92%E5%85%A5%E5%85%83%E7%B4%A0"><span class="toc-text">insert()插入元素</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%B9%98%E6%B3%95%E6%89%A9%E5%B1%95"><span class="toc-text">乘法扩展</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%97%E8%A1%A8%E5%85%83%E7%B4%A0%E7%9A%84%E5%88%A0%E9%99%A4"><span class="toc-text">列表元素的删除</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#del-%E5%88%A0%E9%99%A4"><span class="toc-text">del 删除</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#pop-%E6%96%B9%E6%B3%95"><span class="toc-text">pop()方法</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#remove-%E6%96%B9%E6%B3%95"><span class="toc-text">remove()方法</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%97%E8%A1%A8%E5%85%83%E7%B4%A0%E8%AE%BF%E9%97%AE%E5%92%8C%E8%AE%A1%E6%95%B0"><span class="toc-text">列表元素访问和计数</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E9%80%9A%E8%BF%87%E7%B4%A2%E5%BC%95%E7%9B%B4%E6%8E%A5%E8%AE%BF%E9%97%AE%E5%85%83%E7%B4%A0"><span class="toc-text">通过索引直接访问元素</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#index-%E8%8E%B7%E5%BE%97%E6%8C%87%E5%AE%9A%E5%85%83%E7%B4%A0%E5%9C%A8%E5%88%97%E8%A1%A8%E4%B8%AD%E9%A6%96%E6%AC%A1%E5%87%BA%E7%8E%B0%E7%9A%84%E7%B4%A2%E5%BC%95"><span class="toc-text">index()获得指定元素在列表中首次出现的索引</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#count-%E8%8E%B7%E5%BE%97%E6%8C%87%E5%AE%9A%E5%85%83%E7%B4%A0%E5%9C%A8%E5%88%97%E8%A1%A8%E4%B8%AD%E5%87%BA%E7%8E%B0%E7%9A%84%E6%AC%A1%E6%95%B0"><span class="toc-text">count()获得指定元素在列表中出现的次数</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#len-%E8%BF%94%E5%9B%9E%E5%88%97%E8%A1%A8%E9%95%BF%E5%BA%A6"><span class="toc-text">len()返回列表长度</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%88%90%E5%91%98%E8%B5%84%E6%A0%BC%E5%88%A4%E6%96%AD"><span class="toc-text">成员资格判断</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%87%E7%89%87%E6%93%8D%E4%BD%9C"><span class="toc-text">切片操作</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%97%E8%A1%A8%E7%9A%84%E9%81%8D%E5%8E%86"><span class="toc-text">列表的遍历</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%A4%8D%E5%88%B6%E5%88%97%E8%A1%A8%E6%89%80%E6%9C%89%E7%9A%84%E5%85%83%E7%B4%A0%E5%88%B0%E6%96%B0%E5%88%97%E8%A1%A8%E5%AF%B9%E8%B1%A1"><span class="toc-text">复制列表所有的元素到新列表对象</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%97%E8%A1%A8%E6%8E%92%E5%BA%8F"><span class="toc-text">列表排序</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%BF%AE%E6%94%B9%E5%8E%9F%E5%88%97%E8%A1%A8%EF%BC%8C%E4%B8%8D%E5%BB%BA%E6%96%B0%E5%88%97%E8%A1%A8%E7%9A%84%E6%8E%92%E5%BA%8F"><span class="toc-text">修改原列表，不建新列表的排序</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%BB%BA%E6%96%B0%E5%88%97%E8%A1%A8%E7%9A%84%E6%8E%92%E5%BA%8F"><span class="toc-text">建新列表的排序</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#reversed-%E8%BF%94%E5%9B%9E%E8%BF%AD%E4%BB%A3%E5%99%A8"><span class="toc-text">reversed()返回迭代器</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%97%E8%A1%A8%E7%9B%B8%E5%85%B3%E7%9A%84%E5%85%B6%E4%BB%96%E5%86%85%E7%BD%AE%E5%87%BD%E6%95%B0%E6%B1%87%E6%80%BB"><span class="toc-text">列表相关的其他内置函数汇总</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#max%E5%92%8Cmin"><span class="toc-text">max和min</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#sum"><span class="toc-text">sum</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%A4%9A%E7%BB%B4%E5%88%97%E8%A1%A8"><span class="toc-text">多维列表</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%BA%8C%E7%BB%B4%E5%88%97%E8%A1%A8"><span class="toc-text">二维列表</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%83%E7%BB%84tuple"><span class="toc-text">元组tuple</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%83%E7%BB%84%E7%9A%84%E5%88%9B%E5%BB%BA"><span class="toc-text">元组的创建</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E9%80%9A%E8%BF%87-%E5%88%9B%E5%BB%BA%E5%85%83%E7%BB%84"><span class="toc-text">通过()创建元组</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E9%80%9A%E8%BF%87tuple-%E5%88%9B%E5%BB%BA%E5%85%83%E7%BB%84"><span class="toc-text">通过tuple()创建元组</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%83%E7%BB%84%E7%9A%84%E5%85%83%E7%B4%A0%E8%AE%BF%E9%97%AE%E5%92%8C%E8%AE%A1%E6%95%B0"><span class="toc-text">元组的元素访问和计数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#zip"><span class="toc-text">zip</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%9F%E6%88%90%E5%99%A8%E6%8E%A8%E5%AF%BC%E5%BC%8F%E5%88%9B%E5%BB%BA%E5%85%83%E7%BB%84"><span class="toc-text">生成器推导式创建元组</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%83%E7%BB%84%E6%80%BB%E7%BB%93"><span class="toc-text">元组总结</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AD%97%E5%85%B8"><span class="toc-text">字典</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E5%85%B8%E7%9A%84%E5%88%9B%E5%BB%BA"><span class="toc-text">字典的创建</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E5%85%B8%E5%85%83%E7%B4%A0%E7%9A%84%E8%AE%BF%E9%97%AE"><span class="toc-text">字典元素的访问</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E5%85%B8%E5%85%83%E7%B4%A0%E7%9A%84%E6%B7%BB%E5%8A%A0%E3%80%81%E4%BF%AE%E6%94%B9%E3%80%81%E5%88%A0%E9%99%A4"><span class="toc-text">字典元素的添加、修改、删除</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%BA%8F%E5%88%97%E8%A7%A3%E5%8C%85"><span class="toc-text">序列解包</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%A1%A8%E6%A0%BC%E6%95%B0%E6%8D%AE%E4%BD%BF%E7%94%A8%E5%AD%97%E5%85%B8%E5%92%8C%E5%88%97%E8%A1%A8%E5%AD%98%E5%82%A8%E5%92%8C%E8%AE%BF%E9%97%AE"><span class="toc-text">表格数据使用字典和列表存储和访问</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E5%85%B8%E6%A0%B8%E5%BF%83%E5%BA%95%E5%B1%82%E5%8E%9F%E7%90%86-%E9%87%8D%E8%A6%81"><span class="toc-text">字典核心底层原理(重要)</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%B0%86%E4%B8%80%E4%B8%AA%E9%94%AE%E5%80%BC%E5%AF%B9%E6%94%BE%E8%BF%9B%E5%AD%97%E5%85%B8%E7%9A%84%E5%BA%95%E5%B1%82%E8%BF%87%E7%A8%8B"><span class="toc-text">将一个键值对放进字典的底层过程</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%A0%B9%E6%8D%AE%E9%94%AE%E6%9F%A5%E6%89%BE%E2%80%9C%E9%94%AE%E5%80%BC%E5%AF%B9%E2%80%9D%E7%9A%84%E5%BA%95%E5%B1%82%E8%BF%87%E7%A8%8B"><span class="toc-text">根据键查找“键值对”的底层过程</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9B%86%E5%90%88"><span class="toc-text">集合</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%9B%86%E5%90%88%E5%88%9B%E5%BB%BA%E5%92%8C%E5%88%A0%E9%99%A4"><span class="toc-text">集合创建和删除</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%9B%86%E5%90%88%E7%9B%B8%E5%85%B3%E6%93%8D%E4%BD%9C"><span class="toc-text">集合相关操作</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5"><span class="toc-text">控制语句</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5%E5%92%8C%E9%80%BB%E8%BE%91%E6%80%9D%E7%BB%B4"><span class="toc-text">控制语句和逻辑思维</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%80%89%E6%8B%A9%E7%BB%93%E6%9E%84-%E6%9D%A1%E4%BB%B6%E5%88%A4%E6%96%AD%E7%BB%93%E6%9E%84"><span class="toc-text">选择结构(条件判断结构)</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8D%95%E5%88%86%E6%94%AF%E9%80%89%E6%8B%A9%E7%BB%93%E6%9E%84"><span class="toc-text">单分支选择结构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%9D%A1%E4%BB%B6%E8%A1%A8%E8%BE%BE%E5%BC%8F%E8%AF%A6%E8%A7%A3"><span class="toc-text">条件表达式详解</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8F%8C%E5%88%86%E6%94%AF%E9%80%89%E6%8B%A9%E7%BB%93%E6%9E%84"><span class="toc-text">双分支选择结构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%89%E5%85%83%E6%9D%A1%E4%BB%B6%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-text">三元条件运算符</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%A4%9A%E5%88%86%E6%94%AF%E9%80%89%E6%8B%A9%E7%BB%93%E6%9E%84"><span class="toc-text">多分支选择结构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%80%89%E6%8B%A9%E7%BB%93%E6%9E%84%E7%9A%84%E5%B5%8C%E5%A5%97"><span class="toc-text">选择结构的嵌套</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BE%AA%E7%8E%AF%E7%BB%93%E6%9E%84"><span class="toc-text">循环结构</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#while%E5%BE%AA%E7%8E%AF"><span class="toc-text">while循环</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#for%E5%BE%AA%E7%8E%AF%E5%92%8C%E5%8F%AF%E8%BF%AD%E4%BB%A3%E5%AF%B9%E8%B1%A1%E9%81%8D%E5%8E%86"><span class="toc-text">for循环和可迭代对象遍历</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8F%AF%E8%BF%AD%E4%BB%A3%E5%AF%B9%E8%B1%A1"><span class="toc-text">可迭代对象</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#range%E5%AF%B9%E8%B1%A1"><span class="toc-text">range对象</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B5%8C%E5%A5%97%E5%BE%AA%E7%8E%AF"><span class="toc-text">嵌套循环</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%B5%8C%E5%A5%97%E5%BE%AA%E7%8E%AF%E7%BB%83%E4%B9%A0"><span class="toc-text">嵌套循环练习</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#break%E8%AF%AD%E5%8F%A5"><span class="toc-text">break语句</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#continue%E8%AF%AD%E5%8F%A5"><span class="toc-text">continue语句</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#else%E8%AF%AD%E5%8F%A5"><span class="toc-text">else语句</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%BE%AA%E7%8E%AF%E4%BB%A3%E7%A0%81%E4%BC%98%E5%8C%96%E6%8A%80%E5%B7%A7"><span class="toc-text">循环代码优化技巧</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#zip-%E5%B9%B6%E8%A1%8C%E9%80%81%E4%BB%A3%E5%A4%9A%E4%B8%AA%E5%BA%8F%E5%88%97"><span class="toc-text">zip()并行送代多个序列</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8E%A8%E5%AF%BC%E5%BC%8F%E5%88%9B%E5%BB%BA%E5%BA%8F%E5%88%97"><span class="toc-text">推导式创建序列</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%97%E8%A1%A8%E6%8E%A8%E5%AF%BC%E5%BC%8F"><span class="toc-text">列表推导式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%97%E5%85%B8%E6%8E%A8%E5%AF%BC%E5%BC%8F"><span class="toc-text">字典推导式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%9B%86%E5%90%88%E6%8E%A8%E5%AF%BC%E5%BC%8F"><span class="toc-text">集合推导式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%9F%E6%88%90%E5%99%A8%E6%8E%A8%E5%AF%BC%E5%BC%8F%EF%BC%88%E4%B8%8D%E7%9B%B4%E6%8E%A5%E7%94%9F%E6%88%90%E5%85%83%E7%BB%84%EF%BC%89"><span class="toc-text">生成器推导式（不直接生成元组）</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BB%BC%E5%90%88%E7%BB%83%E4%B9%A0"><span class="toc-text">综合练习</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BB%98%E5%88%B6%E4%B8%8D%E5%90%8C%E9%A2%9C%E8%89%B2%E7%9A%84%E5%90%8C%E5%BF%83%E5%9C%86"><span class="toc-text">绘制不同颜色的同心圆</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E5%92%8C%E5%86%85%E5%AD%98%E5%BA%95%E5%B1%82%E5%88%86%E6%9E%90"><span class="toc-text">函数和内存底层分析</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E7%AE%80%E4%BB%8B"><span class="toc-text">函数简介</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%87%BD%E6%95%B0-function-%E7%9A%84%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5"><span class="toc-text">函数(function)的基本概念</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Python%E5%87%BD%E6%95%B0%E7%9A%84%E5%88%86%E7%B1%BB"><span class="toc-text">Python函数的分类</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E7%9A%84%E5%AE%9A%E4%B9%89%E5%92%8C%E8%B0%83%E7%94%A8"><span class="toc-text">函数的定义和调用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%A0%B8%E5%BF%83%E8%A6%81%E7%82%B9"><span class="toc-text">核心要点</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%BD%A2%E5%8F%82%E5%92%8C%E5%AE%9E%E5%8F%82"><span class="toc-text">形参和实参</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%87%E6%A1%A3%E5%AD%97%E7%AC%A6%E4%B8%B2-%E5%87%BD%E6%95%B0%E7%9A%84%E6%B3%A8%E9%87%8A"><span class="toc-text">文档字符串(函数的注释)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%BF%94%E5%9B%9E%E5%80%BC%E8%AF%A6%E8%A7%A3"><span class="toc-text">返回值详解</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E4%B9%9F%E6%98%AF%E5%AF%B9%E8%B1%A1%EF%BC%8C%E5%86%85%E5%AD%98%E5%BA%95%E5%B1%82%E5%88%86%E6%9E%90"><span class="toc-text">函数也是对象，内存底层分析</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%98%E9%87%8F%E7%9A%84%E4%BD%9C%E7%94%A8%E5%9F%9F-%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F%E5%92%8C%E5%B1%80%E9%83%A8%E5%8F%98%E9%87%8F"><span class="toc-text">变量的作用域(全局变量和局部变量)</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F"><span class="toc-text">全局变量</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B1%80%E9%83%A8%E5%8F%98%E9%87%8F"><span class="toc-text">局部变量</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B1%80%E9%83%A8%E5%8F%98%E9%87%8F%E5%92%8C%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F%E6%95%88%E7%8E%87%E6%B5%8B%E8%AF%95"><span class="toc-text">局部变量和全局变量效率测试</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%82%E6%95%B0%E7%9A%84%E4%BC%A0%E9%80%92"><span class="toc-text">参数的传递</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BC%A0%E9%80%92%E5%8F%AF%E5%8F%98%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%BC%95%E7%94%A8"><span class="toc-text">传递可变对象的引用</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BC%A0%E9%80%92%E4%B8%8D%E5%8F%AF%E5%8F%98%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%BC%95%E7%94%A8"><span class="toc-text">传递不可变对象的引用</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B5%85%E6%8B%B7%E8%B4%9D%E5%92%8C%E6%B7%B1%E6%8B%B7%E8%B4%9D"><span class="toc-text">浅拷贝和深拷贝</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BC%A0%E9%80%92%E4%B8%8D%E5%8F%AF%E5%8F%98%E5%AF%B9%E8%B1%A1%E5%8C%85%E5%90%AB%E7%9A%84%E5%AD%90%E5%AF%B9%E8%B1%A1%E6%98%AF%E5%8F%AF%E5%8F%98%E7%9A%84%E6%83%85%E5%86%B5"><span class="toc-text">传递不可变对象包含的子对象是可变的情况</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%82%E6%95%B0%E7%9A%84%E5%87%A0%E7%A7%8D%E7%B1%BB%E5%9E%8B"><span class="toc-text">参数的几种类型</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%8D%E7%BD%AE%E5%8F%82%E6%95%B0"><span class="toc-text">位置参数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%BB%98%E8%AE%A4%E5%80%BC%E5%8F%82%E6%95%B0"><span class="toc-text">默认值参数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%91%BD%E5%90%8D%E5%8F%82%E6%95%B0-%E5%85%B3%E9%94%AE%E5%AD%97%E5%8F%82%E6%95%B0"><span class="toc-text">命名参数(关键字参数)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8F%AF%E5%8F%98%E5%8F%82%E6%95%B0"><span class="toc-text">可变参数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%BC%BA%E5%88%B6%E5%91%BD%E5%90%8D%E5%8F%82%E6%95%B0"><span class="toc-text">强制命名参数</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#lambda%E8%A1%A8%E8%BE%BE%E5%BC%8F%E5%92%8C%E5%8C%BF%E5%90%8D%E5%87%BD%E6%95%B0"><span class="toc-text">lambda表达式和匿名函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#eval-%E5%87%BD%E6%95%B0"><span class="toc-text">eval()函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%80%92%E5%BD%92%E5%87%BD%E6%95%B0"><span class="toc-text">递归函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B5%8C%E5%A5%97%E5%87%BD%E6%95%B0-%E5%86%85%E9%83%A8%E5%87%BD%E6%95%B0"><span class="toc-text">嵌套函数(内部函数)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#nonlocal%E5%92%8Cglobal%E5%85%B3%E9%94%AE%E5%AD%97"><span class="toc-text">nonlocal和global关键字</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#LEGB%E8%A7%84%E5%88%99"><span class="toc-text">LEGB规则</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1"><span class="toc-text">面向对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%AE%80%E4%BB%8B"><span class="toc-text">面向对象简介</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9D%A2%E5%90%91%E8%BF%87%E7%A8%8B%E5%92%8C%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E6%80%9D%E6%83%B3"><span class="toc-text">面向过程和面向对象思想</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%9D%A2%E5%90%91%E8%BF%87%E7%A8%8B%E5%92%8C%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-text">面向过程和面向对象的区别</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%9D%A2%E5%90%91%E8%BF%87%E7%A8%8B%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="toc-text">面向过程是什么？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="toc-text">面向对象是什么？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E5%92%8C%E9%9D%A2%E5%90%91%E8%BF%87%E7%A8%8B%E6%80%BB%E7%BB%93"><span class="toc-text">面向对象和面向过程总结</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1%E8%BF%9B%E5%8C%96%E7%9A%84%E5%B0%8F%E6%95%85%E4%BA%8B"><span class="toc-text">对象进化的小故事</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B1%BB%E7%9A%84%E5%AE%9A%E4%B9%89"><span class="toc-text">类的定义</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B1%9E%E6%80%A7%E5%92%8C%E6%96%B9%E6%B3%95"><span class="toc-text">属性和方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1%E5%AE%8C%E6%95%B4%E5%86%85%E5%AD%98%E7%BB%93%E6%9E%84"><span class="toc-text">对象完整内存结构</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#init-%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95%E5%92%8C-new-%E6%96%B9%E6%B3%95"><span class="toc-text">__init__构造方法和__new__方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9E%E4%BE%8B%E5%B1%9E%E6%80%A7%E5%92%8C%E5%AE%9E%E4%BE%8B%E6%96%B9%E6%B3%95"><span class="toc-text">实例属性和实例方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%9E%E4%BE%8B%E5%B1%9E%E6%80%A7"><span class="toc-text">实例属性</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%9E%E4%BE%8B%E6%96%B9%E6%B3%95"><span class="toc-text">实例方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E5%92%8C%E6%96%B9%E6%B3%95%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-text">函数和方法的区别</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%9E%E4%BE%8B%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%96%B9%E6%B3%95%E8%B0%83%E7%94%A8%E6%9C%AC%E8%B4%A8"><span class="toc-text">实例对象的方法调用本质</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%B6%E4%BB%96%E6%93%8D%E4%BD%9C"><span class="toc-text">其他操作</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B1%BB%E5%AF%B9%E8%B1%A1%E3%80%81%E7%B1%BB%E5%B1%9E%E6%80%A7%E3%80%81%E7%B1%BB%E6%96%B9%E6%B3%95%E3%80%81%E9%9D%99%E6%80%81%E6%96%B9%E6%B3%95"><span class="toc-text">类对象、类属性、类方法、静态方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%B1%BB%E5%AF%B9%E8%B1%A1"><span class="toc-text">类对象</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%B1%BB%E5%B1%9E%E6%80%A7"><span class="toc-text">类属性</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%86%85%E5%AD%98%E5%88%86%E6%9E%90%E5%AE%9E%E4%BE%8B%E5%AF%B9%E8%B1%A1%E5%92%8C%E7%B1%BB%E5%AF%B9%E8%B1%A1%E5%88%9B%E5%BB%BA%E8%BF%87%E7%A8%8B%EF%BC%88%E9%87%8D%E8%A6%81%EF%BC%89"><span class="toc-text">内存分析实例对象和类对象创建过程（重要）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%B1%BB%E6%96%B9%E6%B3%95"><span class="toc-text">类方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%9D%99%E6%80%81%E6%96%B9%E6%B3%95"><span class="toc-text">静态方法</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#del-%E6%96%B9%E6%B3%95-%E6%9E%90%E6%9E%84%E5%87%BD%E6%95%B0-%E5%92%8C%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E6%9C%BA%E5%88%B6"><span class="toc-text">__del__方法(析构函数)和垃圾回收机制</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#call%E6%96%B9%E6%B3%95%E5%92%8C%E5%8F%AF%E8%B0%83%E7%94%A8%E5%AF%B9%E8%B1%A1"><span class="toc-text">call方法和可调用对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B9%E6%B3%95%E6%B2%A1%E6%9C%89%E9%87%8D%E8%BD%BD"><span class="toc-text">方法没有重载</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B9%E6%B3%95%E7%9A%84%E5%8A%A8%E6%80%81%E6%80%A7"><span class="toc-text">方法的动态性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%A7%81%E6%9C%89%E5%B1%9E%E6%80%A7%E5%92%8C%E7%A7%81%E6%9C%89%E6%96%B9%E6%B3%95-%E5%AE%9E%E7%8E%B0%E5%B0%81%E8%A3%85"><span class="toc-text">私有属性和私有方法(实现封装)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#property%E8%A3%85%E9%A5%B0%E5%99%A8"><span class="toc-text">@property装饰器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B1%9E%E6%80%A7%E5%92%8C%E6%96%B9%E6%B3%95%E5%91%BD%E5%90%8D%E6%80%BB%E7%BB%93"><span class="toc-text">属性和方法命名总结</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B1%BB%E7%BC%96%E7%A0%81%E9%A3%8E%E6%A0%BC"><span class="toc-text">类编码风格</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#None%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%89%B9%E6%AE%8A%E6%80%A7"><span class="toc-text">None对象的特殊性</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#None%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="toc-text">None是什么？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#None%E5%92%8C%E5%85%B6%E4%BB%96%E7%B1%BB%E5%9E%8B%E7%9A%84%E6%AF%94%E8%BE%83"><span class="toc-text">None和其他类型的比较</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%9A%84%E4%B8%89%E5%A4%A7%E7%89%B9%E5%BE%81%E8%AF%B4%E6%98%8E%EF%BC%88%E5%B0%81%E8%A3%85%E3%80%81%E7%BB%A7%E6%89%BF%E3%80%81%E5%A4%9A%E6%80%81%EF%BC%89"><span class="toc-text">面向对象的三大特征说明（封装、继承、多态）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BB%A7%E6%89%BF%E8%AF%A6%E8%A7%A3"><span class="toc-text">继承详解</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%90%E7%B1%BB%E6%89%A9%E5%B1%95%E7%88%B6%E7%B1%BB"><span class="toc-text">子类扩展父类</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%AF%AD%E6%B3%95%E6%A0%BC%E5%BC%8F"><span class="toc-text">语法格式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%B1%BB%E6%88%90%E5%91%98%E7%BB%A7%E6%89%BF%E5%92%8C%E9%87%8D%E5%86%99"><span class="toc-text">类成员继承和重写</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%9F%A5%E7%9C%8B%E7%B1%BB%E7%9A%84%E7%BB%A7%E6%89%BF%E5%B1%82%E6%AC%A1%E7%BB%93%E6%9E%84"><span class="toc-text">查看类的继承层次结构</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#object%E6%A0%B9%E7%B1%BB"><span class="toc-text">object根类</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#dir-%E6%9F%A5%E7%9C%8B%E5%AF%B9%E8%B1%A1%E5%B1%9E%E6%80%A7"><span class="toc-text">dir()查看对象属性</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%87%8D%E5%86%99-str-%E6%96%B9%E6%B3%95"><span class="toc-text">重写__str__()方法</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A4%9A%E9%87%8D%E7%BB%A7%E6%89%BF"><span class="toc-text">多重继承</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MRO%E6%96%B9%E6%B3%95%E8%A7%A3%E6%9E%90%E9%A1%BA%E5%BA%8F"><span class="toc-text">MRO方法解析顺序</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#super-%E8%8E%B7%E5%BE%97%E7%88%B6%E7%B1%BB%E7%9A%84%E5%AE%9A%E4%B9%89"><span class="toc-text">super()获得父类的定义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A4%9A%E6%80%81%E8%AF%A6%E8%A7%A3"><span class="toc-text">多态详解</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%89%B9%E6%AE%8A%E6%96%B9%E6%B3%95%E5%92%8C%E8%BF%90%E7%AE%97%E7%AC%A6%E9%87%8D%E8%BD%BD"><span class="toc-text">特殊方法和运算符重载</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%89%B9%E6%AE%8A%E5%B1%9E%E6%80%A7"><span class="toc-text">特殊属性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%B5%85%E6%8B%B7%E8%B4%9D%E5%92%8C%E6%B7%B1%E6%8B%B7%E8%B4%9D"><span class="toc-text">对象的浅拷贝和深拷贝</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B5%85%E6%8B%B7%E8%B4%9D"><span class="toc-text">浅拷贝</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B7%B1%E6%8B%B7%E8%B4%9D"><span class="toc-text">深拷贝</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BB%84%E5%90%88"><span class="toc-text">组合</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F"><span class="toc-text">设计模式</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F%E5%AE%9E%E7%8E%B0"><span class="toc-text">工厂模式实现</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%E5%AE%9E%E7%8E%B0"><span class="toc-text">单例模式实现</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B7%A5%E5%8E%82%E5%92%8C%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%E7%BB%93%E5%90%88%E8%B5%B7%E6%9D%A5"><span class="toc-text">工厂和单例模式结合起来</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Python%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA"><span class="toc-text">Python开发环境搭建</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/archives/6ca065c5.html" title="SanShui API 使用教程"><img src="http://wallpaper.csun.site/?abc" onerror="this.onerror=null;this.src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="SanShui API 使用教程"/></a><div class="content"><a class="title" href="/archives/6ca065c5.html" title="SanShui API 使用教程">SanShui API 使用教程</a><time datetime="2025-03-13T13:21:12.311Z" title="更新于 2025-03-13 21:21:12">2025-03-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/b5700173.html" title="微信小程序定时订阅消息问题"><img src="http://wallpaper.csun.site/?25" onerror="this.onerror=null;this.src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="微信小程序定时订阅消息问题"/></a><div class="content"><a class="title" href="/archives/b5700173.html" title="微信小程序定时订阅消息问题">微信小程序定时订阅消息问题</a><time datetime="2024-10-17T12:04:53.379Z" title="更新于 2024-10-17 20:04:53">2024-10-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/638889b7.html" title="深度学习回归任务训练代码模版"><img src="http://wallpaper.csun.site/?24" onerror="this.onerror=null;this.src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="深度学习回归任务训练代码模版"/></a><div class="content"><a class="title" href="/archives/638889b7.html" title="深度学习回归任务训练代码模版">深度学习回归任务训练代码模版</a><time datetime="2024-10-17T12:04:09.066Z" title="更新于 2024-10-17 20:04:09">2024-10-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/7cb9f0a8.html" title="通过nginx访问tomcat中SpringMVC应用"><img src="http://wallpaper.csun.site/?23" onerror="this.onerror=null;this.src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="通过nginx访问tomcat中SpringMVC应用"/></a><div class="content"><a class="title" href="/archives/7cb9f0a8.html" title="通过nginx访问tomcat中SpringMVC应用">通过nginx访问tomcat中SpringMVC应用</a><time datetime="2024-10-17T12:02:23.321Z" title="更新于 2024-10-17 20:02:23">2024-10-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/d4b1abad.html" title="下载M3U8格式加密视频"><img src="http://wallpaper.csun.site/?22" onerror="this.onerror=null;this.src='/./img/config_img/%E5%A4%9C%E6%99%9A.jpg'" alt="下载M3U8格式加密视频"/></a><div class="content"><a class="title" href="/archives/d4b1abad.html" title="下载M3U8格式加密视频">下载M3U8格式加密视频</a><time datetime="2024-10-17T12:02:02.720Z" title="更新于 2024-10-17 20:02:02">2024-10-17</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('http://wallpaper.csun.site/?4')"><div id="footer-wrap"><div class="footer_custom_text">更多内容查看<a target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/huaiyuechusan/">我的GitHub</a> ！</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button><button id="go-down" type="button" title="直达底部" onclick="btf.scrollToDest(document.body.scrollHeight, 500)"><i class="fas fa-arrow-down"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.1
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container').forEach(node => {
            if (node.hasAttribute('display')) {
              btf.wrap(node, 'div', { class: 'mathjax-overflow' })
            } else {
              btf.wrap(node, 'span', { class: 'mathjax-overflow' })
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax/es5/tex-mml-chtml.min.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>function loadLivere () {
  if (typeof LivereTower === 'object') {
    window.LivereTower.init()
  }
  else {
    (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
    })(document, 'script');
  }
}

if ('Livere' === 'Livere' || !true) {
  if (true) btf.loadComment(document.getElementById('lv-container'), loadLivere)
  else loadLivere()
}
else {
  function loadOtherComment () {
    loadLivere()
  }
}</script></div><div class="aplayer no-destroy" data-id="875151895" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="true" data-volume="0.5"> </div><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-show-text.min.js" data-mobile="false" data-text="Nice,To,Meet,YOU" data-fontsize="15px" data-random="false" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["meta[property=\"og:image\"]","meta[property=\"og:title\"]","meta[property=\"og:url\"]","head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>
    function butterfly_categories_card_injector_config(){
      var parent_div_git = document.getElementById('recent-posts');
      var item_html = '<style>li.categoryBar-list-item{width:32.3%;}.categoryBar-list{max-height: 380px;overflow:auto;}.categoryBar-list::-webkit-scrollbar{width:0!important}@media screen and (max-width: 650px){.categoryBar-list{max-height: 320px;}}</style><div class="recent-post-item" style="height:auto;width:100%;padding:0px;"><div id="categoryBar"><ul class="categoryBar-list"><li class="categoryBar-list-item" style="background:url(./img/config_img/image-20231112202739060-2023-11-1220-27-56.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/AI大模型/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">AI大模型</a><span class="categoryBar-list-count">3</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/202310300007012-2023-11-1123-30-55.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/微信小程序/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">微信小程序</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/Girl-2023-11-2221_46_26.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/爬虫/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">爬虫</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/202310300007316-2023-11-1123-30-57.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/深度学习/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">深度学习</a><span class="categoryBar-list-count">4</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/Cat-2023-11-2221-47-16.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/大数据/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">大数据</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/preview-2024-1-8-17-36-46.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/PyTorch/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">PyTorch</a><span class="categoryBar-list-count">3</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/preview-2024-1-8-17-36-11.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/多模态推荐系统/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">多模态推荐系统</a><span class="categoryBar-list-count">1</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/Starry-Night-in-Anime-Wallpaper-2023-11-2221-46-39.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/学习总结/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">学习总结</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/page_img/wallhaven-y8lqo7.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/竞赛/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">竞赛</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/preview-2024-1-8-17-34-25.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Python/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">Python</a><span class="categoryBar-list-count">4</span><span class="categoryBar-list-descr"></span></li><li class="categoryBar-list-item" style="background:url(./img/config_img/preview-2024-1-8-17-37-57.jpg);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Liunx/&quot;);" href="javascript:void(0);" rel="external nofollow noreferrer">Liunx</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr"></span></li></ul></div></div>';
      console.log('已挂载butterfly_categories_card')
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      }
    if( document.getElementById('recent-posts') && (location.pathname ==='/'|| '/' ==='all')){
    butterfly_categories_card_injector_config()
    }
  </script><script data-pjax>
  function butterfly_footer_beautify_injector_config(){
    var parent_div_git = document.getElementById('footer-wrap');
    var item_html = '<div id="workboard"></div><p id="ghbdages"><a class="github-badge" target="_blank" href="https://hexo.io/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="博客框架为Hexo_v6.2.0" title=""><img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&amp;logo=hexo" alt=""/></a><a class="github-badge" target="_blank" href="https://butterfly.js.org/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="主题版本Butterfly_v4.3.1" title=""><img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&amp;logo=bitdefender" alt=""/></a><a class="github-badge" target="_blank" href="https://github.com/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="本站采用多线部署，主线路托管于Github Pages" title=""><img src="https://img.shields.io/badge/Hosted-Github Pages-brightgreen?style=flat&amp;logo=Github" alt=""/></a><a class="github-badge" target="_blank" href="https://gitee.com/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="本站采用多线部署，备用线路托管于Gitee Pages" title=""><img src="https://img.shields.io/badge/Hosted-Gitee Pages-22DDDD?style=flat&amp;logo=Gitee" alt=""/></a><a class="github-badge" target="_blank" href="https://github.com/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="本站项目由Github托管" title=""><img src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&amp;logo=GitHub" alt=""/></a><a class="github-badge" target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow noreferrer" style="margin-inline:5px" data-title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可" title=""><img src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&amp;logo=Claris" alt=""/></a></p>';
    console.log('已挂载butterfly_footer_beautify')
    parent_div_git.insertAdjacentHTML("beforeend",item_html)
    }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_footer_beautify_injector_config();
  }
  else if (epage === cpage){
    butterfly_footer_beautify_injector_config();
  }
  </script><script async src="/./js/runtime.js"></script><!-- hexo injector body_end end --></body></html>